一款移動應用能在市場上長期站穩腳跟,離不開三件事:功能實用、體驗出色、外觀精緻。而精緻外觀背後除了美工的辛苦設計,還需要開發者懂得如何正確地展示這些素材——否則再好的設計也會被糟糕的拉伸毁掉。
舉個例子。下面這張圖本意是拿來做按鈕背景的:
button.png,尺寸為 24x60
現在把它設為一個 150x50 按鈕的背景:
CGSize viewSize = self.view.bounds.size; UIButton *button = [[UIButton alloc] init]; button.bounds = CGRectMake(0, 0, 150, 50); button.center = CGPointMake(viewSize.width * 0.5f, viewSize.height * 0.5f); UIImage *image = [UIImage imageNamed:@"button"]; [button setBackgroundImage:image forState:UIControlStateNormal]; [self.view addSubview:button];
運行效果:

結果慘不忍睹。原因很簡單:原圖只有 24x60,被全方位拉伸成 150x50 之後,四個圓角首當其衝地變形了。
有人可能立刻想到:讓美工把圖做大一點不就完了?這確實是一種解法,但不值得推薦——圖片變大會同時推高安裝包體積和內存占用,何況還有更好的辦法。
仔細觀察會發現,真正難看的是被拉伸的四角,中間區域的拉伸幾乎不影響觀感。所以結論很清晰:拉伸時只處理中間那一塊矩形區域,邊緣部分保持原樣。
比如下圖中,只拉伸中間的矩形區域,上下左右四條邊都不動:

iOS 提供了相應的 API。截至 iOS 6.0,一共有三代方案,下面逐一說明。
iOS 早期引入了「端蓋」的概念,用來標明圖片中哪些部分不參與拉伸。下圖中黑色代表需要被拉伸的區域,上下左右不需要拉伸的邊緣就是端蓋。

通過設置端蓋寬度,可以得到一個已處理過的 UIImage 對象:
-(UIImage*)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
這個方法只有兩個參數:leftCapWidth 是左端蓋寬度,topCapHeight 是頂端蓋高度。系統會自動推算右端蓋與底端蓋:
rightCapWidth = width - leftCapWidth - 1; bottomCapHeight = height - topCapHeight - 1;
代進來算一下可拉伸區域:
stretchWidth = width - leftCapWidth - rightCapWidth = 1; stretchHeight = height - topCapHeight - bottomCapHeight = 1;
也就是說,可拉伸區域固定只有 1x1,邊緣和四角完全不動。
使用示例:
NSInteger leftCapWidth = image.size.width * 0.5f; NSInteger topCapHeight = image.size.height * 0.5f; image = [image stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
注意該方法返回的是一個新對象,原 image 不變,因此必須把返回值重新賦回變量。
運行效果:

按鈕終於恢復了該有的樣子。
兩個注意點:此法從 iOS 5.0 起被標記為過時;且它只能拉伸 1x1 的區域。
iOS 5.0 提供了新的接口:
-(UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
它只接收一個 UIEdgeInsets 參數,可以分別指定上下左右四個端蓋的尺寸:
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 在同一方法基礎上多了一個參數:
-(UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
新增的 resizingMode 用於指定填充方式:
UIImageResizingModeStretch:拉伸模式,把 UIEdgeInsets 圈出的矩形區域拉伸鋪滿。UIImageResizingModeTile:平鋪模式,把該矩形區域重複鋪排填充。image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
運行效果:
