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

问题描述:

看哪: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?

你对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

一个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];