iOS图片拉伸的三种方法

方法一:

iOS中有个叫端盖(end cap)的概念,用来指定图片中的哪一部分不用拉伸,上下左右不需要被拉伸的边缘就称为端盖。

1 // use resizableImageWithCapInsets: and capInsets. 
3 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight __TVOS_PROHIBITED;
4 @property(nonatomic,readonly) NSInteger leftCapWidth __TVOS_PROHIBITED;   // default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1
5 @property(nonatomic,readonly) NSInteger topCapHeight __TVOS_PROHIBITED;   // default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1
1  // 拉伸区域距离左端宽度  
2  NSInteger leftCapWidth = image.size.width * 0.5f;  
3  // 拉伸区域距离顶端高度  
4  NSInteger topCapHeight = image.size.height * 0.5f;  
5  // 重新给image赋值  
6  image = [image stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight]; 

方法二:

通过设置UIEdgeInsets的left、right、top、bottom来分别指定图片拉伸区域距离左端宽度、右端宽度、顶端高度、底端高度
//通过设置UIEdgeInsets的left、right、top、bottom来分别指定图片拉伸区域距离左端宽度、右端宽度、顶端高度、底端高度
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0); // create a resizable version of this image. the interior is tiled when drawn.
CGFloat top = 10// 拉伸区域距离顶端高度
CGFloat bottom = 10 ; // 拉伸区域距离底端高度
CGFloat left = 20// 拉伸区域距离左端宽度
CGFloat right = 20// 拉伸区域距离右端宽度
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
// 拉伸重新给image赋值
image = [image resizableImageWithCapInsets:insets];

方法三:

在iOS6.0中,UIImage又提供了一个方法处理图片拉伸,对比iOS5.0中的方法,多了一个UIImageResizingMode参数,用来指定拉伸的模式:
UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片
/*
*在iOS6.0中,UIImage又提供了一个方法处理图片拉伸,对比iOS5.0中的方法,多了一个UIImageResizingMode参数,用来指定拉伸的模式: * UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片 * UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片 */ - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode
CGFloat top = 10// 拉伸区域距离顶端高度
CGFloat bottom = 10 ; //拉伸区域距离底端高度
CGFloat left = 20// 拉伸区域距离左端宽度
CGFloat right = 20// 拉伸区域距离右端宽度
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
// 拉伸后重新给image赋值
 image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
原文地址:https://www.cnblogs.com/somebodywx/p/5724752.html