您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 圖片拉伸:用 cap insets 讓按鈕背景不再變形

編輯:iOS 開發綜合

這個時代是看臉的,App 的介面就是它的臉。漂亮的視覺背後有 UI 設計師的心血,但如果開發時隨便拉伸,設計就白做了。

以下面這張用來當按鈕背景的圖為例,原始尺寸是 59 × 32。

直接拉伸會發生什麼事

先把它放進一個 200 × 50 的 imageView 中:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self stretchPhoto];
}

- (void)stretchPhoto {
    UIImageView *imageView =
        [[UIImageView alloc] initWithFrame:CGRectMake(60, 180, 200, 50)];
    imageView.image = [UIImage imageNamed:@"btnbg_blue.png"];
    [self.view addSubview:imageView];
}

執行後可以清楚看到,圖片的四個圓角全變形了。原因很直白:原圖 59 × 32,被硬撐到 200 × 50,邊緣的細節跟著被拉開。

指定拉伸點

- (void)stretchPhoto {
    UIImageView *imageView =
        [[UIImageView alloc] initWithFrame:CGRectMake(60, 180, 200, 50)];
    [self.view addSubview:imageView];

    UIImage *images = [UIImage imageNamed:@"btnbg_blue.png"]; // 59 * 32
    images = [images stretchableImageWithLeftCapWidth:30 topCapHeight:16];
    imageView.image = images;
}

這次四個角保持原樣,只有中間被延展,視覺上就正常多了。

方法參數怎麼看

Apple 的定義是:

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth
                               topCapHeight:(NSInteger)topCapHeight;

@property (nonatomic, readonly) NSInteger leftCapWidth;
// default is 0. if non-zero, horiz. stretchable.
// right cap is calculated as width - leftCapWidth - 1

@property (nonatomic, readonly) NSInteger topCapHeight;
// default is 0. if non-zero, vert. stretchable.
// bottom cap is calculated as height - topCapWidth - 1

這兩個參數一般稱為「端蓋」(cap),分別是左端蓋寬與頂端蓋高。指定之後,右側與底部的端蓋由官方公式推算:

rightCapWidth  = image.size.width  - (image.leftCapWidth  + 1)
bottomCapHeight = image.size.height - (image.topCapHeight + 1)

也就是說,最終真正被拉伸的,是「左端蓋與頂端蓋交叉處旁邊那個 1 × 1 的點」。這個點會沿著水平與垂直方向複製填滿,其餘四邊則保持原樣。這也是為什麼圆角不會變形。

實務上常見的做法是傳入寬與高的一半(例如 30 與 16),如此一來即使設計稿邊緣有細微變化,也不容易出現意料之外的拉伸結果。

現代寫法

stretchableImageWithLeftCapWidth:topCapHeight: 在 iOS 5 之後已被標記為廢棄。目前應改用 UIImage 的 resizableImageWithCapInsets:,或直接改用 - (void)resizableImageWithCapInsets: 搭配 Auto Layout 的九宮格拉伸。若是在 Storyboard 中設定,也可以直接把 image asset 的 Slicing 屬性拉好,讓系統自動處理,不必寫程式碼。

UIImage *img = [[UIImage imageNamed:@"btnbg_blue.png"]
    resizableImageWithCapInsets:UIEdgeInsetsMake(16, 30, 16, 29)
                  resizingMode:UIImageResizingModeStretch];
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved