代码部分
- (void)viewDidLoad {
[super viewDidLoad];
UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 200, 200)];
layerView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:layerView];
UIImage *image = [UIImage imageNamed:@"bg"];
layerView.layer.contents = (__bridge id)image.CGImage;
/** 设置对齐模式
kCAGravityCenter
kCAGravityTop
kCAGravityBottom
kCAGravityLeft
kCAGravityRight
kCAGravityTopLeft
kCAGravityTopRight
kCAGravityBottomLeft
kCAGravityBottomRight
kCAGravityResize
kCAGravityResizeAspect
kCAGravityResizeAspectFill
*/
layerView.layer.contentsGravity = kCAGravityResize;
}
运行效果图
层级关系图