2011-02-23 39 views
4

看哪:iOS - 可以拉伸UIImageView而不是UIButton?

//UIImageView* stretchTest = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]]; 
//[self addSubview:stretchTest]; 


UIButton *stretchTest = [UIButton buttonWithType:UIButtonTypeCustom]; 
[stretchTest setFrame:CGRectMake(0, 0, 400, 100)]; 
[stretchTest setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal]; 
[self addSubview:stretchTest]; 

stretchTest.contentStretch = CGRectMake(0.5, 0.5, 0, 0); 
stretchTest.contentMode = UIViewContentModeScaleToFill; 

CGRect frame = stretchTest.frame; 
frame.size.height = 300; 
stretchTest.frame = frame; 

使用的UIImageView(以上註釋)中,圖像適當地拉伸 - 圓角保持正確的半徑,因爲只有圖像的中心像素被拉伸。

使用UIButton,圖像被拉伸不正確。角落半徑不被維護,並且變得醜陋。

UIImageView和UIButton都是UIView的子類。爲什麼按鈕調整大小不同於imageView?

回答

11

你對UIButton的工作方式做出了假設。它的實現方式與UIImageView不同。 UIImageView只是一個視圖,沒有子視圖,其內容就是圖像。 UIButton是不同的,它的工作方式是一個私有的實現細節。

如果您試圖在按鈕上適當地拉伸圖像,應該使用-[UIImage stretchableImageWithLeftCapWidth:topCapHeight:]來獲取知道應該如何拉伸的UIImage。如果你想舒展只是中間的像素,可以使用類似

UIImage *image = [UIImage imageNamed:@"image.png"]; 
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)]; 
+0

ok ...確實有效。我正在嘗試使用上述內容,因爲根據Apple的說法「在爲視圖指定背景時,使用contentStretch屬性優於創建可伸縮UIImage對象。」他們沒有提及任何有關UIView的哪些子類可以或不可以使用該屬性的內容。 – sol 2011-02-23 01:48:28

+1

在按鈕上可用的contentStretch足以滿足我寫過的功能(現在兩次!)一個UIButton子類,它將UIImageView插入到自身中,並將其背景圖像(和contentStretch)複製到它們中。這並不難。唯一的小問題是重寫'LayoutSubviews'來將imageViews移動到後面,以便它們出現在按鈕的非背景圖像和標題標籤後面。 – rgeorge 2011-02-24 06:20:21

0

一個UIButton有兩類它可以顯示圖片 - 前景圖像和背景圖像。預計按鈕的背景圖像將取代按鈕的背景紋理。因此,它將延伸到填充整個背景。該按鈕的前景圖像應該是一個圖標,可能會或可能不會顯示在文本旁邊;它不會伸展。它可能收縮,如果框架比圖像小,但它不會伸展。

按鈕的前景和背景圖像可以在代碼中設置這樣的:

// stretchy 
[self setBackgroundImage:backgroundImage forState:UIControlStateNormal]; 

// not stretchy 
[self setImage:forgroundImage forState:UIControlStateNormal]; 

默認情況下,一個按鈕backgroundImage將使用scaleToFill伸展的形象。如果你需要使用cap insets來拉伸圖像,你應該將它們設置在圖像上,然後將其指定給backgroundImage,如下所示:

UIImage *image = [UIImage imageNamed:@"bg_image.png"]; 

/* This assumes your image will have a 1px column and 1px row of pixels 
    in the horizontal and vertical middle of the image that should be 
    stretchable. If that's not the case (such as asymetrical buttons) 
    you need to adjust the caps */ 
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) 
       topCapHeight:floorf(image.size.height/2)]; 
[self setBackgroundImage:image forState:UIControlStateNormal];