iOS图片拉伸技巧(iOS5.0、iOS6.0)

2020-01-18 20:06:41王旭

使用UIImage的这个方法,可以通过设置端盖宽度返回一个经过拉伸处理的UIImage对象

 

复制代码 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight; 这个方法只有2个参数,leftCapWidth代表左端盖宽度,topCapHeight代表顶端盖高度。系统会自动计算出右端盖宽度(rightCapWidth)和底端盖高度(bottomCapHeight),算法如下:

 


 // width为图片宽度
 rightCapWidth = width - leftCapWidth - 1;
 
 // height为图片高度
 bottomCapHeight = height - topCapHeight - 1

经过计算,你会发现中间的可拉伸区域只有1x1


// stretchWidth为中间可拉伸区域的宽度
 stretchWidth = width - leftCapWidth - rightCapWidth = 1;
  
 // stretchHeight为中间可拉伸区域的高度
 stretchHeight = height - topCapHeight - bottomCapHeight = 1;

因此,使用这个方法只会拉伸图片中间1x1的区域,并不会影响到边缘和角落。

下面演示下方法的使用:


// 左端盖宽度
NSInteger leftCapWidth = image.size.width * 0.5f;
// 顶端盖高度
NSInteger topCapHeight = image.size.height * 0.5f;
// 重新赋值
image = [image stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];

调用这个方法后,原来的image并不会发生改变,会产生一个新的经过拉伸的UIImage,所以第6行中需要将返回值赋值回给image变量

运行效果:

iOS,图片拉伸

可以发现,图片非常美观地显示出来了

注意:

1.这个方法在iOS 5.0出来后就过期了

2.这个方法只能拉伸1x1的区域

 

二、iOS 5.0

在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];

运行效果:

iOS,图片拉伸

三、iOS 6.0

在iOS6.0中,UIImage又提供了一个方法处理图片拉伸