

- - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
- // width为图片宽度
- rightCapWidth = width - leftCapWidth - 1;
- // height为图片高度
- bottomCapHeight = height - topCapHeight - 1
经过计算,你会发现中间的可拉伸区域只有1x1
[java] view plain copy
- // stretchWidth为中间可拉伸区域的宽度
- stretchWidth = width - leftCapWidth - rightCapWidth = 1;
- // stretchHeight为中间可拉伸区域的高度
- stretchHeight = height - topCapHeight - bottomCapHeight = 1;
因此,使用这个方法只会拉伸图片中间1x1的区域,并不会影响到边缘和角落。
下面演示下方法的使用:
[java] view plain copy
- // 左端盖宽度
- NSInteger leftCapWidth = image.size.width * 0.5f;
- // 顶端盖高度
- NSInteger topCapHeight = image.size.height * 0.5f;
- // 重新赋值
- image = [image stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
- - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
- CGFloat top = 25; // 顶端盖高度
- CGFloat bottom = 25 ; // 底端盖高度
- CGFloat left = 10; // 左端盖宽度
- CGFloat right = 10; // 右端盖宽度
- UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
- // 伸缩后重新赋值
- image = [image resizableImageWithCapInsets:insets];
三、iOS 6.0
在iOS6.0中,UIImage又提供了一个方法处理图片拉伸
[java] view plain copy
- - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
对比iOS5.0中的方法,只多了一个UIImageResizingMode参数,用来指定拉伸的模式:
- UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
- UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片

可以拿到图片直接在xcode右侧设置,会自动计算保护区域