背景图片的拉伸
2016-07-30 本文已影响27人
eryuxinling
// 1.1 创建UIImage对象
UIImage *image = [UIImage imageNamed:@"buttongreen"];
// 1.2 拿到image的尺寸
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
// 1.3 返回一张受保护而且拉伸的图片--->CapInsets:哪些地方要保护
// 方式一:
(1)UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageHeight * 0.5, imageWidth * 0.5, imageHeight * 0.5 - 1, imageWidth * 0.5 - 1)];
/*
UIImageResizingModeTile, 平铺
UIImageResizingModeStretch, 拉伸(伸缩)
*/
(2)UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageHeight * 0.5, imageWidth * 0.5, imageHeight * 0.5 - 1, imageWidth * 0.5 - 1) resizingMode:UIImageResizingModeTile];
// 方式二:
// 右边需要被保护的区域 = 图片的width - leftCapWidth - 1
// 底部需要被保护的区域(bottom cap) = height - topCapHeight - 1
UIImage *resizableImage = [image stretchableImageWithLeftCapWidth:imageWidth * 0.5 topCapHeight:imageHeight * 0.5];
// 2.把图片设置到按钮上
[self.button setBackgroundImage:resizableImage forState:UIControlStateNormal];
由于可能在项目中很多地方要用到图片拉伸方法,所以把它定义成为一个类扩展
#import <UIKit/UIKit.h>
@interface UIImage (SJMExtention)
/**
* 返回一张受保护的图片(被拉伸的)
*/
+ (instancetype)resizableImageWithLocalImageName:(NSString *)localImageName;
@end
#import "UIImage+SJMExtention.h"
@implementation UIImage (SJMExtention)
+ (instancetype)resizableImageWithLocalImageName:(NSString *)localImageName {
// 创建图片对象
UIImage *image = [UIImage imageNamed:localImageName];
// 获取图片的尺寸
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
return [image stretchableImageWithLeftCapWidth:imageWidth * 0.5 topCapHeight:imageHeight * 0.5];
}
@end