- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 160, 80)];
btn.layer.cornerRadius = 5.0f;
btn.layer.masksToBounds = YES;
UIImage *img = [UIImage imageNamed:@"button_red"];
CGFloat scale = img.size.width / img.size.height;
NSLog(@"scale = %f",scale);
CGFloat btnImageW = img.size.width * 0.5;
CGFloat btnImageH = img.size.height * 0.5;
UIImage *newBtnImage = [img resizableImageWithCapInsets:UIEdgeInsetsMake(btnImageH, btnImageW, btnImageH, btnImageW) resizingMode:UIImageResizingModeStretch];
[btn setBackgroundImage: newBtnImage forState:UIControlStateNormal];
[self.view addSubview:btn];
}
button设置背景图时被拉伸.png
button设置图片预期效果.png
[btn setBackgroundImage: img forState:UIControlStateNormal];
[self.view addSubview:btn];
可见图片的原始尺寸比例 scale = 4.512195 , 而实际按钮的比例为 2:1 , 故此直接将原始图片设置成button的背景图片时就会得到一些意想不到的拉伸效果,若想让图片更好的适应按钮的尺寸需要对原始图片进行一些处理,这里官方推荐了一种方法:
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets;
Parameters说明:
capInsets The values to use for the cap insets.
这里上下左右的间距取的是原始图片宽高的1/2
这里是一段官方文档说明:
You use this method to add cap insets to an image or to change the existing cap insets of an image. In both cases, you get back a new image and the original image remains untouched. For example, you can use this method to create a background image for a button with borders and corners: when the button is resized, the corners of the image remain unchanged, but the borders and center of the image expand to cover the new size.
原理:当按钮调整大小时,图像的边角保持不变,但图像的边框和中心将展开以覆盖新尺寸。
网友评论