contents属性
CALayer的contents属性,为id类型,意味着可以是任何类型对象。中间需要做类型转换。
layer.contents = (__bridge id)image.CGImage;//这是在ARC下
例如给view1加载一张图片
UIImage *image = [UIImage imageNamed:@”p1.jpg”];
self.view1.layer.contents = (__bridge id)image.CGImage;
图片是铺满图层的,可以设置contentGravity来改变加载状况。
layer.contentsGravity = kCAGravityResizeAspect;
设置不同的
contentsGravity值将达到不同的效果。
contentScale 属性定义了寄宿图像和视图大小的比例。当用代码设置寄宿图像时,一定要设置contentScale属性
blueLayer.contentsScale = [[UIScreen mainScreen] scale];
maskToBounds
设置超出边界部分是否显示。
contentsRect 属性允许我们在视图层里面线束寄宿图像的一个子域。用于图片分割
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"p1.jpg"];
//图片分割
[self addSpriteImage:image WithContentReact:CGRectMake(0, 0, 0.5, 0.5) WithLayer:self.view1.layer];
[self addSpriteImage:image WithContentReact:CGRectMake(0.5, 0, 0.5, 0.5) WithLayer:self.view3.layer];
[self addSpriteImage:image WithContentReact:CGRectMake(0, 0.5, 0.5, 0.5) WithLayer:self.view2.layer];
[self addSpriteImage:image WithContentReact:CGRectMake(0.5, 0.5, 0.5, 0.5) WithLayer:self.view4.layer];
}
-(void)addSpriteImage:(UIImage *)image WithContentReact:(CGRect)react WithLayer:(CALayer *)layer{
layer.contents = (__bridge id)image.CGImage;
layer.contentsRect =react;
layer.contentsGravity = kCAGravityResizeAspect;
}
contentsCenter
属性用于设置图层拉伸位置,定义了一个固定的边框和一个在图层上可拉伸区域
在CALayer上面绘制。要遵守CALayerDelegate代理协议,首先会生成一个上下文用于绘制。
-(void)addSpriteImage:(UIImage *)image WithContentReact:(CGRect)react WithLayer:(CALayer *)layer在此代理中绘制
- (void)viewDidLoad {
[super viewDidLoad];
CALayer *blueLayer = [CALayer layer];
blueLayer.backgroundColor = [UIColor blueColor].CGColor;
blueLayer.frame = CGRectMake(50, 50, 100, 100);
blueLayer.contentsScale = [[UIScreen mainScreen] scale];
[self.view1.layer addSublayer:blueLayer];
blueLayer.delegate = self;
[blueLayer display];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
CGContextSetLineWidth(ctx, 10.0);
CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
CGContextStrokeEllipseInRect(ctx, layer.bounds);
}