方法一
iOS中有个叫端盖(end cap)的概念,用来指定图片中的哪一部分不用拉伸.比如下图中,黑色代表需要被拉伸的矩形区域,上下左右不需要被拉伸的边缘就称为端盖

使用UIImage的这个方法,可以通过设置端盖宽度返回一个经过处理的UIImage对象
-(UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth
topCapHeight:(NSInteger)topCapHeight
这个方法只有两个参数,leftCapWidth代表左端盖宽度,topCapHeight代表顶端盖高度。系统会自动计算出右端盖宽度(rightCapWidth)和底端盖高度(bottomCapHeight),算法如下:
// width为图片宽度
rightCapWidth = width - leftCapWidth - 1;
// height为图片高度
bottomCapHeight = height - topCapHeight - 1;
经过计算,会发现中间的可拉伸区域只有1*1
// stretchWidth为中间可拉伸区域的宽度
stretchWidth = width - leftCapWidth - rightCapWidth = 1;
//stretchHeight为中间可拉伸区域的高度
stretchHeight = height - topCapHeight - bottomCapHeight = 1;
因此,使用这个方法只会拉伸图片中间1*1的区域,并不会影响到边缘和角落。
下面演示下这个方法的使用
//做端盖宽度
NSInteger leftCapWidth = image.size.width * 0.5f;
//顶端盖高度
NSInteger topCapHeight = image.size.height * 0.5f;
//重新赋值
image = [image stretchableImageWithCapWidth:leftCapWidth topCapHeight:topCapHeight];
调用这个方法之后,原来的image并不会发生改变,会产生一个新的经过拉伸的UIImage,所以需要将返回值赋值给image变量。但是注意这个方法只能拉伸1*1的区域。
方法二
- 在iOS 5.0中,UIImage又有一个新方法可以处理图片的拉伸问题
-(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
这个方法只接收一个UIEdgeInsets类型的参数,可以通过设置UIEdgeInsets的left,right,top,bottom来分别指定左端盖宽度、右端盖宽度、顶端盖高度、低端盖高度
CGFloat top = 25; // 顶端盖高度
CGFloat bottom = 25 ; // 底端盖高度
CGFloat left = 10; // 左端盖宽度
CGFloat right = 10; // 右端盖宽度
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
// 伸缩后重新赋值
image = [image resizableImageWithCapInsets:insets];
- 在iOS6.0中,UIImage又提供了一个方法处理图片拉伸
-(UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:
(UIImageResizingMode)resizingMode
对比上一个方法,只是多了一个UIImageResizingMode参数,用来指定拉伸的模式:
- UIImageResizingModeStrech:拉伸模式,通过拉伸UIEgdeInsets指定的矩形区域来填充图片
- UIImageResizingModeTile:平铺模式,通过重复显示UIEgdeInsets指定的矩形区域来填充图片
本文转载自明杰老师的博客https://blog.csdn.net/q199109106q/article/details/8615661
网友评论