在項(xiàng)目中有的圖片需要拉伸處理(比如QQ聊天信息的Message Button背景圖片)仅仆,常用的有兩種方式:
一. 參考李明杰博客:iOS圖片拉伸技巧
iOS中提供很好用的API幫我們實(shí)現(xiàn)上述功能止潘。到iOS 6.0為止企量,iOS提供了3種圖片拉伸的解決方案铜幽,接下來分別詳細(xì)介紹這些方案驴剔。
<pre>
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets;
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode;
</pre>
1抄沮、iOS 5.0之前
iOS中有個(gè)叫端蓋(end cap)的概念跋核,用來指定圖片中的哪一部分不用拉伸岖瑰。比如下圖中,黑色代表需要被拉伸的矩形區(qū)域砂代,上下左右不需要被拉伸的邊緣就稱為端蓋蹋订。
<pre>
- (UIImage *)resizableImageWithName:(NSString *)name
{
UIImage *normal = [UIImage imageNamed:name];
// 左端蓋寬度
NSInteger leftCapWidth = normal.size.width * 0.5f;
// 頂端蓋高度
NSInteger topCapHeight = normal.size.height * 0.5f;
// 重新賦值
return [normal stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
}
</pre>
2、iOS 5.0
<pre>+ (UIImage *)resizableImageWithName:(NSString *)name
{
UIImage *normal = [UIImage imageNamed:name];
CGFloat w = normal.size.width * 0.5;
CGFloat h = normal.size.height * 0.5;
return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];
}</pre>
3刻伊、iOS 6.0
對(duì)比iOS5.0中的方法露戒,只多了一個(gè)UIImageResizingMode參數(shù),用來指定拉伸的模式:
UIImageResizingModeStretch:拉伸模式捶箱,通過拉伸UIEdgeInsets指定的矩形區(qū)域來填充圖片
UIImageResizingModeTile:平鋪模式智什,通過重復(fù)顯示UIEdgeInsets指定的矩形區(qū)域來填充圖片
二. 在xcode中設(shè)置圖片的Slices
Top,Bottom,Height是Xcode默認(rèn)設(shè)置的最優(yōu)參數(shù),可以根據(jù)需要實(shí)際調(diào)整丁屎。
點(diǎn)擊Slices后可以看到:
Tiles:填充
Stretches:拉伸
直接按右下角的 Show Slicing可以很直觀的設(shè)置具體拉伸那個(gè)部位