引入两个类拓展 UIView+LM.h 和 CALayer+LMXYWH.h
//www.greatytc.com/p/03d38e6e25f9
#import "ViewController.h"
@interface ViewController ()<CALayerDelegate>
@property (strong,nonatomic)UIView *layerView;
@end
@implementation ViewController
#pragma mark - 控制器生命周期
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
#pragma mark - setupUI
-(void)setupUI
{
self.view.backgroundColor = [UIColor grayColor];
self.layerView = [[UIView alloc]init];
self.layerView.backgroundColor = [UIColor whiteColor];
self.layerView.W = 200;
self.layerView.H = 200;
self.layerView.center = SCREEN_CENTER;
[self.view addSubview:self.layerView];
//CALayer 的 contents 属性 展示一张图片
UIImage *image = [UIImage imageNamed:@"girl1.jpeg"];
self.layerView.layer.contents = (__bridge id)image.CGImage;
//1.1
//contentsGravity 决定内容在图层的边界中的对齐方式
self.layerView.layer.contentsGravity = kCAGravityResizeAspect;
//contentsScale 目的不是放大!!
//contentsGravity 会影响 contentsScale
//contentsScale 用来判断在绘制图层的时候应该为寄宿图创建的空间大小, 和需要显示的图片的拉伸度,类似于UIView中的contentScaleFactor
/**
//1.2
self.layerView.layer.contentsGravity =kCAGravityCenter;
self.layerView.layer.contentsScale = image.scale;
//2 maskToBounds
self.layerView.layer.masksToBounds = YES;
*/
//3 contentsRect 显示寄宿图中一个子域 0-1之间 是相对值
//self.layerView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);
//4 contentsCenter 在 Interface Builder 里可以配置 Stretching
// self.layerView.layer.contentsCenter = CGRectMake(0.25, 0.25, 0.5, 0.5);
}
@end