ios开发那些事iOS人间不知德-iOS老本行

iOS - CALayer添加背景图片

2019-04-19  本文已影响116人  lizhi_boy

给一个视图添加背景图通用的做法是:定义一个UIImageView然后添加在视图上面。现在我们用一个比较不常用的一个做法,那就是利用Layer的图层设置图片

实现代码如下:

UIView *layerView = [UIView new];
 layerView.frame = CGRectMake(90, 90, 200, 200);
 layerView.backgroundColor = [UIColor whiteColor];
 layerView.layer.contents = (id)[UIImage imageNamed:@"testImage"].CGImage;
 layerView.layer.contentsGravity = @"resizeAspect";
 [self.view addSubview:layerView];

说明一下layercontentscontentsGravity属性

/* A string defining how the contents of the layer is mapped into its
 * bounds rect. Options are `center', `top', `bottom', `left',
 * `right', `topLeft', `topRight', `bottomLeft', `bottomRight',
 * `resize', `resizeAspect', `resizeAspectFill'. The default value is
 * `resize'. Note that "bottom" always means "Minimum Y" and "top"
 * always means "Maximum Y". */

都看到这里了,给个❤️不过分吧

上一篇下一篇

猜你喜欢

热点阅读