蘋果為了節(jié)省打包文件(ipa)的存儲空間,在iOS5就推出了圖片拉伸,但是初衷是好的,如果程序猿不會用,那一切都是白搭
-
1.正常圖片
-
2.如果這樣設(shè)置,由于按鈕的尺寸比圖片的尺寸大,所以顯示的樣子是
-
3.圖片拉伸,拉伸分為兩種
先來分析圖片拉伸原理,中間的紅色區(qū)域就是拉伸的區(qū)域
- 3.1.第一種是圖形化界面,
-
3.1.1有storyboard(UIImageView能拉伸)
- 3.1.2 UIButton(不能使用這種方式拉伸)
-
- 3.1.第一種是圖形化界面,
- 3.2.第二種拉伸方式切片(Show Slicing)
- 4.接下來用代碼拉伸
- 4.1 stretchableImageWithLeftCapWidth:topCapHeight:
// 1.設(shè)置登錄按鈕的背景圖片
UIImage *image = self.loginBtn.currentBackgroundImage;
// 返回一張可拉伸的圖片
// 這個方法只能拉伸1x1的區(qū)域
// Width: x軸哪里拉伸(不拉伸區(qū)域)
// Height: 從y軸哪里拉伸(不拉伸區(qū)域)
image = [image stretchableImageWithLeftCapWidth:image.size.width / 2 topCapHeight:image.size.height / 2];
[self.loginBtn setBackgroundImage:image forState:UIControlStateNormal];
注意: 此方法在iOS5.0過期
- 系統(tǒng)會根據(jù)傳入的兩個參數(shù)自動計算出拉伸的范圍
算法如下:
// stretchWidth為中間可拉伸區(qū)域的寬度
stretchWidth = width - leftCapWidth - rightCapWidth = 1;
// stretchHeight為中間可拉伸區(qū)域的高度
stretchHeight = height - topCapHeight - bottomCapHeight = 1;
- 4.2.-(UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)capInsets(在iOS5.0出的方法)
這個方法只接收一個UIEdgeInsets類型的參數(shù)匙握,可以通過設(shè)置UIEdgeInsets的left供璧、right唯袄、top、bottom來分別指定左端蓋寬度匀们、右端蓋寬度、頂端蓋高度准给、底端蓋高度
CGFloat top = 100; // 頂端蓋高度
CGFloat bottom = 100 ; // 底端蓋高度
CGFloat left = 1; // 左端蓋寬度
CGFloat right = 1; // 右端蓋寬度
UIEdgeInsets capInsets = UIEdgeInsetsMake(top, left, bottom, right);
// 重新賦值
image = [image resizableImageWithCapInsets: capInsets];
- 4.3-(UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode(iOS6.0之后的方法)
- capInsets參數(shù)和上面的參數(shù)相同
-
resizingMode:
- UIImageResizingModeTile:平鋪模式,通過重復(fù)顯示UIEdgeInsets指定的矩形區(qū)域來填充圖片
- UIImageResizingModeStretch:拉伸模式,通過拉伸UIEdgeInsets指定的矩形區(qū)域來填充圖片
參考文章:http://blog.csdn.net/q199109106q/article/details/8615661