- iOS中提供很好用的API幫我們實(shí)現(xiàn)上述功能。到iOS 6.0為止,iOS提供了3種圖片拉伸的解決方案,接下來(lái)分別詳細(xì)介紹這些方案
一、iOS 5.0之前
- iOS中有個(gè)叫端蓋(end cap)的概念
- 用來(lái)指定圖片中的哪一部分不用拉伸
比如下圖中良哲,黑色代表需要被拉伸的矩形區(qū)域,上下左右不需要被拉伸的邊緣就稱(chēng)為端蓋
屏幕快照 2016-06-06 上午9.26.35.png
- 用來(lái)指定圖片中的哪一部分不用拉伸
使用UIImage的這個(gè)方法助隧,可以通過(guò)設(shè)置端蓋寬度返回一個(gè)經(jīng)過(guò)拉伸處理的UIImage對(duì)象
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
這個(gè)方法只有2個(gè)參數(shù)筑凫,leftCapWidth代表左端蓋寬度滑沧,topCapHeight代表頂端蓋高度。系統(tǒng)會(huì)自動(dòng)計(jì)算出右端蓋寬度(rightCapWidth)和底端蓋高度(bottomCapHeight)巍实,算法如下
// width為圖片寬度
rightCapWidth = width - leftCapWidth - 1;
// height為圖片高度
bottomCapHeight = height - topCapHeight - 1
經(jīng)過(guò)計(jì)算滓技,你會(huì)發(fā)現(xiàn)中間的可拉伸區(qū)域只有1x1
// stretchWidth為中間可拉伸區(qū)域的寬度
stretchWidth = width - leftCapWidth - rightCapWidth = 1;
// stretchHeight為中間可拉伸區(qū)域的高度
stretchHeight = height - topCapHeight - bottomCapHeight = 1;
注意:這個(gè)方法的局限性
1.這個(gè)方法在iOS 5.0出來(lái)后就過(guò)期了
2.這個(gè)方法只能拉伸1x1的區(qū)域
二、iOS 5.0
- 在iOS 5.0中棚潦,UIImage又有一個(gè)新方法可以處理圖片的拉伸問(wèn)題
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
這個(gè)方法只接收一個(gè)UIEdgeInsets類(lèi)型的參數(shù)令漂,可以通過(guò)設(shè)置UIEdgeInsets的left、right丸边、top叠必、bottom來(lái)分別指定左端蓋寬度、右端蓋寬度妹窖、頂端蓋高度纬朝、底端蓋高度
CGFloat top = 25; // 頂端蓋高度
CGFloat bottom = 25 ; // 底端蓋高度
CGFloat left = 10; // 左端蓋寬度
CGFloat right = 10; // 右端蓋寬度
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
// 伸縮后重新賦值
image = [image resizableImageWithCapInsets:insets];
iOS 6.0
- 在iOS6.0中,UIImage又提供了一個(gè)方法處理圖片拉伸
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
對(duì)比iOS5.0中的方法骄呼,只多了一個(gè)UIImageResizingMode參數(shù)共苛,用來(lái)指定拉伸的模式:
- UIImageResizingModeStretch:拉伸模式,通過(guò)拉伸UIEdgeInsets指定的矩形區(qū)域來(lái)填充圖片
- UIImageResizingModeTile:平鋪模式蜓萄,通過(guò)重復(fù)顯示UIEdgeInsets指定的矩形區(qū)域來(lái)填充圖片
CGFloat top = 25; // 頂端蓋高度
CGFloat bottom = 25 ; // 底端蓋高度
CGFloat left = 10; // 左端蓋寬度
CGFloat right = 10; // 右端蓋寬度
UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
// 指定為拉伸模式隅茎,伸縮后重新賦值
image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
- 在Xcode中對(duì)圖片的拉伸處理
- UIImageView
注意:UIButton不可以使用這種方式拉伸
- UIImageView
Snip20160606_6.png
X 代表:從X方向上那個(gè)位置開(kāi)始拉伸 (取值范圍0~1)
Y 代表:從Y方向上那個(gè)位置開(kāi)始拉伸 (取值范圍0~1)
width 代表X軸方向上拉伸多少像素(寫(xiě)0代表拉伸一像素)
height 代表Y軸方向上拉伸多少像素(寫(xiě)0代表拉伸一像素)
- 第二種Xcode中對(duì)圖片處理
Snip20160606_11.png
Snip20160606_12.png
Snip20160606_13.png
Snip20160606_8.png
注意:默認(rèn)的拉伸方式是平鋪 這里可以修改方式
Snip20160606_14.png