之前写过一篇使用 UIImage 的 resizableImageWithCapInsets 方法来进行图片拉伸的文章《图片拉伸 UIImage resizableImageWithCapInsets》,今天看 CALayer 的 contents 属性,发现也有实现图片拉伸的方法,学习一下。
首先来看一下拉伸的结果图:
第一个图是拉伸的结果,第二个是原图。
这个拉伸效果使用的是 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;
这段文字介绍了该属性的用法,白话点说,拉伸时它可以将图片分割成 3 * 3 的区域,每一块的具体操作可参考下图(来自 iOS 核心动画高级技巧一书),中间绿色的区域可以在两个方向进行拉伸,蓝色区域只能在水平方向进行拉伸,而红色部分则在垂直方法拉伸。默认情况下,contentsCenter 是 {0, 0, 1, 1},下图展示了contentsCenter设置为{0.25, 0.25, 0.5, 0.5}的效果
了解了该属性,下面就要对我们的图像进行拉伸,对于我们来说,我们只想拉伸红色边框里面的内容,前面的放大镜图像不应该进行拉伸,会变形。
因此我们要设置好拉伸的部位,下图中黑色框中位置就是 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];
跑出来效果就是第一张图的样子。这里注意一定要设置 view.layer.contentsScale = image.scale,否则图片在Retina 设备会显示不正确,这是因为CGImage和UIImage不同,没有拉伸的概念。当我们使用UIImage类去读取图片的时候,读取了高质量的Retina版本的图片。但是用CGImage来设置图层的时候,拉伸这个因素在转换的时候就丢失了。