1 #import "ViewController.h"
2
3 @interface ViewController ()
4
5 @end
6
7 @implementation ViewController
8
9 - (void)viewDidLoad {
10 [super viewDidLoad];
11 // 對圖片的拉伸
12 [self stretchPhoto];
13 }
14
15 - (void)stretchPhoto
16 {
17 UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 180, 200, 50)];
18 imageView.image = [UIImage imageNamed:@"btnbg_blue.png"];
19 [self.view addSubview:imageView];
20 }
21
22 @end
我們可以清晰的看到,圖片失去了原來的樣子,尤其是四個角,這是因為圖片本身大小為:59 * 32,而設置的圖片顯示位置的大小為200 * 50 ,圖片被拉壞了. 下面我們對這張圖片設置一個拉伸點:
1 #import "ViewController.h"
2
3 @interface ViewController ()
4
5 @end
6
7 @implementation ViewController
8
9 - (void)viewDidLoad {
10 [super viewDidLoad];
11
12 // 對圖片的拉伸
13 [self stretchPhoto];
14 }
15
16 // 對圖片的拉伸
17 - (void)stretchPhoto
18 {
19 UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(60, 180, 200, 50)];
20 [self.view addSubview:imageView];
21
22 // 設置圖片的拉伸點
23 UIImage *images = [UIImage imageNamed:@"btnbg_blue.png"]; // 59 * 32
24 images = [images stretchableImageWithLeftCapWidth:30 topCapHeight:16];
25 imageView.image = images;
26 }
27
28 @end
可以清楚的看到圖片被完美的拉伸顯示了. 下面對設置圖片拉伸點的方法做一個詳解:
1 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight; 2 @property(nonatomic,readonly) NSInteger leftCapWidth; // default is 0. if non-zero, horiz. stretchable. right cap is calculated as width - leftCapWidth - 1 3 @property(nonatomic,readonly) NSInteger topCapHeight; // default is 0. if non-zero, vert. stretchable. bottom cap is calculated as height - topCapWidth - 1
上面的內容是Xcode文檔中對該方法的解釋 第1行是方法名,返回值為UIImage對象,需要傳遞兩個NSInteger類型的參數; 第2行和第3行是第1行需要傳遞參數的兩個屬性,默認都是0;從其他地方看到這兩個屬性由一個名字叫:端蓋,即左端蓋寬和頂端蓋高. 這樣看來,拉伸圖片的話,左側和頂部都拉伸了,那麼右側和底部呢? API文檔給出了計算公式:rightCapWidth = image.size.width - (image.leftCapWidth + 1); 即:右端蓋寬 = 圖片寬 - (左端蓋寬 + 1); bottomCapHeight = image.size.height - (image.topCapHeight + 1); 即:底部端蓋 = 圖片高 - (頂部端蓋 + 1); 這樣可以看出,最後被拉伸的位置就是給定左端蓋和頂部端蓋交叉位置旁邊 1 * 1 的區域(中間黃色區域),即這種方式只拉伸給定區域的 1 * 1 個點. 一般來說,習慣給定圖片寬和高一半的位置,這樣可以避免不清楚邊緣變化引起的不必要的麻煩.