两种方法实现图片的拉伸效果
一.分类实现
为UIImage创建一个分类 HPImageStretch
UIImage+HPImageStretch.h的代码:
+(instancetype)resizableImageWithImageName:(NSString *)imageName;
UIImage+HPImageStretch.m的代码:
+(instancetype)resizableImageWithImageName:(NSString *)imageName
{
UIImage *image = [UIImage imageNamed:imageName];
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
/*UIImageResizingMode:
UIImageResizingModeTile, 平铺(默认)
UIImageResizingModeStretch,拉伸
*/
//三种实现方法
/*
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageHeight*0.5, imageWidth*0.5, imageHeight*0.5-1, imageWidth*0.5-1)];
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageHeight*0.5, imageWidth*0.5, imageHeight*0.5-1, imageWidth*0.5-1) resizingMode:UIImageResizingModeTile];
*/
return [image stretchableImageWithLeftCapWidth:imageWidth*0.5 topCapHeight:imageHeight*0.5];
}
调用示例如下
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(20, 100, 200, 300);
[button setBackgroundImage:[UIImage resizableImageWithImageName:@"chat_send_nor"] forState:UIControlStateNormal];
二.在Assets.xcassets里对图片做改动
1.选中Assets.xcassets文件夹
2.如图一选中要拉伸的图片
3.选中图片
4.默认系统会给出一定的拉伸数据,如果不合适,开发人员可以根据自己图片的实际情况在红色框里做改动