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

sol*_*sol 5 uibutton uiview uiimageview ios

看吧:

//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;
Run Code Online (Sandbox Code Playgroud)

使用UIImageView(上面已注释),图像适当拉伸 - 圆角保持正确的半径,因为只有图像的中心像素被拉伸.

使用UIButton,图像被错误地拉​​伸.角半径没有保持,它变得丑陋.

UIImageView和UIButton都是UIView的子类.为什么按钮的调整大小与imageView不同?

Lil*_*ard 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)];
Run Code Online (Sandbox Code Playgroud)