之前寫過一篇使用 UIImage 的 resizableImageWithCapInsets 方法來進(jìn)行圖片拉伸的文章《圖片拉伸 UIImage resizableImageWithCapInsets》抓韩,今天看 CALayer 的 contents 屬性,發(fā)現(xiàn)也有實現(xiàn)圖片拉伸的方法放祟,學(xué)習(xí)一下吻贿。
首先來看一下拉伸的結(jié)果圖:
第一個圖是拉伸的結(jié)果唆姐,第二個是原圖。
這個拉伸效果使用的是 contents 的 contentsCenter 屬性
/* A rectangle in normalized image coordinates defining the scaled
* center part of the `contents' image.
*
* When an image is resized due to its `contentsGravity' property its
* center part implicitly defines the 3x3 grid that controls how the
* image is scaled to its drawn size. The center part is stretched in
* both dimensions; the top and bottom parts are only stretched
* horizontally; the left and right parts are only stretched
* vertically; the four corner parts are not stretched at all. (This is
* often called "9-slice scaling".)
*
* The rectangle is interpreted after the effects of the `contentsRect'
* property have been applied. It defaults to the unit rectangle [0 0 1
* 1] meaning that the entire image is scaled. As a special case, if
* the width or height is zero, it is implicitly adjusted to the width
* or height of a single source pixel centered at that position. If the
* rectangle extends outside the [0 0 1 1] unit rectangle the result is
* undefined. Animatable. */
@property CGRect contentsCenter;
這段文字介紹了該屬性的用法,白話點(diǎn)說奉芦,拉伸時它可以將圖片分割成 3 * 3 的區(qū)域赵抢,每一塊的具體操作可參考下圖(來自 iOS 核心動畫高級技巧一書),中間綠色的區(qū)域可以在兩個方向進(jìn)行拉伸声功,藍(lán)色區(qū)域只能在水平方向進(jìn)行拉伸烦却,而紅色部分則在垂直方法拉伸。默認(rèn)情況下先巴,contentsCenter 是 {0, 0, 1, 1}其爵,下圖展示了contentsCenter設(shè)置為{0.25, 0.25, 0.5, 0.5}的效果
了解了該屬性,下面就要對我們的圖像進(jìn)行拉伸伸蚯,對于我們來說摩渺,我們只想拉伸紅色邊框里面的內(nèi)容,前面的放大鏡圖像不應(yīng)該進(jìn)行拉伸剂邮,會變形摇幻。
因此我們要設(shè)置好拉伸的部位,下圖中黑色框中位置就是 contentsCenter 的(x, y) 值挥萌,綠色部分的長寬就是要拉伸的部分绰姻。
直接上代碼
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor yellowColor];
[self.view addSubview:view];
UIImage *image = [UIImage imageNamed:@"questionTextViewSearchNormal"];
view.frame = CGRectMake(100, 100, image.size.width + 100, image.size.height);
view.layer.contents = (__bridge id)image.CGImage;
view.layer.contentsCenter = CGRectMake(0.6, 0, 0.3, 1);
view.layer.contentsScale = image.scale;
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 200, image.size.width, image.size.height)];
view1.backgroundColor = [UIColor yellowColor];
view1.layer.contents = (__bridge id)image.CGImage;
[self.view addSubview:view1];
跑出來效果就是第一張圖的樣子。這里注意一定要設(shè)置 view.layer.contentsScale = image.scale引瀑,否則圖片在Retina 設(shè)備會顯示不正確狂芋,這是因為CGImage和UIImage不同,沒有拉伸的概念憨栽。當(dāng)我們使用UIImage類去讀取圖片的時候帜矾,讀取了高質(zhì)量的Retina版本的圖片。但是用CGImage來設(shè)置圖層的時候屑柔,拉伸這個因素在轉(zhuǎn)換的時候就丟失了黍特。