- 如果不采用相應技術對button的背景圖片進行拉伸,則顯示的效果就會失真,效果:
Snip20160823_7.png
- iOS中有三種方法對圖片進行拉伸
// 方法一:
- (void)viewDidLoad {
[super viewDidLoad];
// 0.創建一張圖片
UIImage *image = [UIImage imageNamed:@"chat_send_nor"];
// 1.獲取圖片尺寸
CGFloat width = image.size.width;
CGFloat height = image.size.height;
// 2.拉伸圖片
UIImage *resizableImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(height * 0.5, width * 0.5, height * 0.5 - 1, width * 0.5 - 1)];
// 3.把拉伸過的圖片設置為button的背景圖片
[self.buttonView setBackgroundImage:resizableImage forState:UIControlStateNormal];
}
// 方法二
- (void)viewDidLoad {
[super viewDidLoad];
// 0.創建一張圖片
UIImage *image = [UIImage imageNamed:@"chat_send_nor"];
// 1.獲取圖片尺寸
CGFloat width = image.size.width;
CGFloat height = image.size.height;
// 2.拉伸圖片
UIImage *resizableImage = [image stretchableImageWithLeftCapWidth:width * 0.5 topCapHeight:height * 0.5];
// 3.把拉伸過的圖片設置為button的背景圖片
[self.buttonView setBackgroundImage:resizableImage forState:UIControlStateNormal];
}
- 方法三
-
在storyboard中進行設置
Snip20160823_8.png
-
Snip20160823_9.png
Snip20160823_12.png
- 注意:由于storyboard的圖片拉伸往往不能處理一些特殊形狀的圖片,所以還需要用上面兩種代碼拉伸圖片的方法
- 由于經常需要用到代碼拉伸圖片的功能,所以我們可以寫一個分類,可以方便以后直接使用
- 構造一個類方法
Snip20160823_13.png
#import "UIImage+LHLExtension.h"
@implementation UIImage (LHLExtension)
+ (instancetype)stretchableImageWithLocalName:(NSString *)imageName{
// 0.創建一張圖片
UIImage *image = [UIImage imageNamed:imageName];
// 1.獲取圖片尺寸
CGFloat width = image.size.width;
CGFloat height = image.size.height;
// 2.拉伸圖片
UIImage *resizableImage = [image stretchableImageWithLeftCapWidth:width * 0.5 topCapHeight:height * 0.5];
return resizableImage;
}
@end
- 然后在viewDidLoad中用分類中的方法
UIImage *image = [UIImage stretchableImageWithLocalName:@"chat_send_nor"];
[self.buttonView setBackgroundImage:image forState:UIControlStateNormal];
}
- 以上三種方式處理后的圖片效果如下:
Snip20160823_14.png