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的子类。 为什么按钮的resize与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)]; 

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