注:本文翻譯自國外iOS開發者Natasha The Robot的一篇博文,鏈接在此。
在iOS應用中,經常會有很多Button有相同的背景圖片,卻由於處在不同的位置而大小不同(盡管在iOS7中Button已經沒有背景圖片了)。比如,一個功能為“Save”的Button要比功能為“Submit”要窄一些,但是他們都可以擁有紫色背景。
在這篇文章中,你不需要為每個button准備不同的背景圖片。你很幸運,因為iOS的UIEdgeInsetsMake方法可以很方便的把這張圖片:
變成這張:
解決辦法很簡單:較小的圖片的四個圓角保持不變,中間部分可以在豎直與水平方向上復制,這樣,圖片的中間部分就可以按照你的要求來放大了。
可以通過UIEdgeInsets來實現這個功能:你可以在拉伸圖片時,在圖片中上、左、下、右四個邊緣指定出不允許拉伸的部分。UIEdgeInsets本身是一個結構體,包含四個float類型的浮點數:
- typedef struct {
- CGFloat top, left, bottom, right;
- } UIEdgeInsets;
代替全部
我新建了一個項目:在stordboard中我添加了一個自定義的Button,然后在ViewController中為其創建了一個Outlet。在我的ViewDidLoad:方法中,我調用了私有方法configureButton,它通過UIEdgeInsetsMake(0,0,0,0)來構建了一個UIEdgeInsets:
- - (void)configureButton
- {
- UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
- UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]
- resizableImageWithCapInsets:edgeInsets];
- [self.purpleButton setBackgroundImage:backgroundButtonImage
- forState:UIControlStateNormal];
- }
由於沒有為指定不拉伸區域(四個方向上不允許拉伸的區域都設置為0),所以是整個圖片在水平和豎直方向上復制,結果如下:
豎直限定
給圖片添加豎直限定,我們需要向下面這個示意圖一樣忽略掉左右兩個邊緣:
在兩條豎線間的區域可以在水平方向上復制。可以忽略掉左右兩邊各留8個像素的距離,將UIEdgeInsets設置為UIEdgeInsetsMake(0,8,0,8):
- - (void)configureButton
- {
- UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
- UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]
- resizableImageWithCapInsets:edgeInsets];
- [self.purpleButton setBackgroundImage:backgroundButtonImage
- forState:UIControlStateNormal];
- }
結果看起來好多了:
水平限定
相似的,如果你想為圖片添加水平方向的限定,可以忽略掉距上下邊緣各8個像素的距離,僅復制兩條線之間的區域:
將UIEdgeInsets設置為UIEdgeInsetsMake(8,0,8,0):
- - (void)configureButton
- {
- UIEdgeInsets edgeInsets = UIEdgeInsetsMake(8, 0, 8, 0);
- UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]
- resizableImageWithCapInsets:edgeInsets];
- [self.purpleButton setBackgroundImage:backgroundButtonImage
- forState:UIControlStateNormal];
- }
結果如下:
在兩個方向上進行限定
如果希望在水平和豎直方向上都對可以復制區域加以限定,我們需要將上、下、左、右四個邊緣的內側8個像素的區域都忽略掉:
將UIEdgeInsets設置為UIEdgeInsetsMake(8,8,8,8):
- - (void)configureButton
- {
- UIEdgeInsets edgeInsets = UIEdgeInsetsMake(8, 8, 8, 8);
- UIImage *backgroundButtonImage = [[UIImage imageNamed:@"purple_button.png"]
- resizableImageWithCapInsets:edgeInsets];
- [self.purpleButton setBackgroundImage:backgroundButtonImage
- forState:UIControlStateNormal];
- }
太棒了!我們現在有一個正確顯示的Button了:
現在,如果你需要其他紫色的button,你只需要把剛才那個小正方形的圖片的四個邊忽略掉,然后將圖片中間部分按照你希望的大小進行復制就可以了。Enjoy!
轉:http://blog.csdn.net/xiaoyulong007/article/details/25658815