UIImageView 的contentMode這個(gè)屬性是用來(lái)設(shè)置圖片的顯示方式,如居中、居右,是否縮放等,有以下幾個(gè)常量可供設(shè)定:
typedefNS_ENUM(NSInteger, UIViewContentMode) {
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,// contents scaled to fit with fixed aspect. remainder is transparent
UIViewContentModeScaleAspectFill,// contents scaled to fill with fixed aspect. some portion of content may be clipped.
UIViewContentModeRedraw,// redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter,// contents remain same size. positioned adjusted.
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
};
以上幾個(gè)常量,凡是沒有帶Scale的,當(dāng)圖片尺寸超過 ImageView尺寸時(shí),只有部分顯示在ImageView中。UIViewContentModeScaleToFill屬性會(huì)導(dǎo)致圖片變形。UIViewContentModeScaleAspectFit會(huì)保證圖片比例不變,而且全部顯示在ImageView中,這意味著ImageView會(huì)有部分空白。UIViewContentModeScaleAspectFill也會(huì)證圖片比例不變,但是是填充整個(gè)ImageView的,可能只有部分圖片顯示出來(lái)。
self.image = UIViewContentModeScaleToFill;如圖1

self.image = UIViewContentModeScaleAspectFit;如圖2

self.image = UIViewContentModeScaleAspectFill;如圖3

其他屬性,可以根據(jù)字面意思來(lái)理解,分別是顯示圖片中間的范圍,顯示圖片頭部的范圍,以此類推。
所以大家在開發(fā)過程中,圖片變形了的話,簡(jiǎn)單設(shè)置一下就好了。
還有一種需求,就是當(dāng)需要僅僅把圖片的內(nèi)容拉伸,而邊角不拉伸的情況,類似于聊天窗口的氣泡,可拉伸長(zhǎng)短,而圖片邊角不失貞變形,就是需要用這個(gè)方法:
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
這個(gè)函數(shù)是UIImage的一個(gè)實(shí)例函數(shù),它的功能是創(chuàng)建一個(gè)內(nèi)容可拉伸,而邊角不拉伸的圖片,需要兩個(gè)參數(shù),第一個(gè)是不拉伸區(qū)域和左邊框的寬度,第二個(gè)參數(shù)是不拉伸區(qū)域和上邊框的寬度。
第一次用這個(gè)函數(shù)的時(shí)候一直搞不懂為什么只要兩個(gè)參數(shù)就行,至少應(yīng)該指定左上角和右下角,總共四個(gè)參數(shù)啊。后來(lái)讀讀文檔才明白,只需要兩個(gè)參數(shù)就行了。
根據(jù)設(shè)置的寬度和高度,將接下來(lái)的一個(gè)像素進(jìn)行左右擴(kuò)展和上下拉伸。
注意:可拉伸的范圍都是距離leftCapWidth后的1豎排像素,和距離topCapHeight后的1橫排像素。
參數(shù)的意義是,如果參數(shù)指定10,5。那么,圖片左邊10個(gè)像素,上邊5個(gè)像素。不會(huì)被拉伸,x坐標(biāo)為11和一個(gè)像素會(huì)被橫向復(fù)制,y坐標(biāo)為6的一個(gè)像素會(huì)被縱向復(fù)制。注意:只是對(duì)一個(gè)像素進(jìn)行復(fù)制到一定寬度。而圖像后面的剩余像素也不會(huì)被拉伸。
UIImage*imageTest = [UIImageimageNamed:@"rounded"];
UIImageView*imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(40,63,240,128)];
UIImage*newImageTest = [imageTeststretchableImageWithLeftCapWidth:imageTest.size.width*0.5topCapHeight:imageTest.size.height*0.5];
[imageViewsetImage:newImageTest];
[self.viewaddSubview:imageView];
原來(lái)是這樣的:

圖片本來(lái)是這樣的:

設(shè)置后,圖片顯示是這樣的:

當(dāng)然如果在Xib或者StoryBoard中可以通過View 的Stretching屬性來(lái)設(shè)置。

也能達(dá)到這樣的效果。