1、直接拉伸
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 100)];
UIImage *image = [UIImage imageNamed:@"123"];
image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
imageView.image = image;
[self.view addSubview:imageView];
stretchable可拉伸的,要传两个参数
// default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1
// default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1
默认为0,是整个直接拉伸的,所以直接设置可能会发生形变或者模糊很丑,第一个参数是设置左边不被拉伸的尺寸,我们默认设置为宽度的一半,右边会自动设置为:Image.size.width - leftCapWidth - 1,所以中间可拉伸的尺寸为1,同理topCapHeight也是一样,所以中间可被拉伸的frame为1 x 1。
2、设置不被拉伸的区域
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 100)];
UIImage *image = [UIImage imageNamed:@"123"];
image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.5 -1, image.size.width * 0.5 -1, image.size.height * 0.5 -1, image.size.width * 0.5 -1) resizingMode:UIImageResizingModeStretch];
imageView.image = image;
[self.view addSubview:imageView];
CapInsets这里设置的为不被拉伸的区域,如果上下设置为高度的一半 - 1,左右设置为宽度一半 - 1,则拉伸区域为 2 x 2,当然上下直接设置为高度一半,左右设置为宽度一半也是有效;resizingMode为显示的模式:UIImageResizingModeTile为平铺模式,UIImageResizingModeStretch为拉伸模式。
3、直接在Assets.xcassets里设置
在Assets.xcassets中选中该图片,右边有一个slicing的属性,选择Horizontal and Vertical ,center选中Stretches,width和height默认为1 x 1