Cowboy Tech

iOS项目015.CALayer简介

Set UIImageView CALayer

- (void)initImgView{
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpg"]];
imgView.frame = CGRectMake((kScreenWidth - 200)/2, (kScreenHeight - 200)/2, 200, 200);
[self.view addSubview:imgView];
.............
}

图像的CALayer层 - 阴影

//1.设置阴影
imgView.layer.shadowColor = [UIColor yellowColor].CGColor;
//2.阴影的偏移大小
imgView.layer.shadowOffset = CGSizeMake(10, 10);
//3.阴影的不透明度
imgView.layer.shadowOpacity = 0.5;

图像的CALayer层 - 圆角

//4.设置圆角大小
imgView.layer.cornerRadius = 10;//设置圆角半径为10
imgView.layer.masksToBounds = YES;//强制内部的所有子层支持圆角效果,少了这个设置,UIImageView是不会有圆角效果的。设置之后,没有阴影效果

图像的CALayer层 - 边框

//5.设置边框
imgView.layer.borderWidth = 5;
imgView.layer.borderColor = [UIColor grayColor].CGColor;

图像的CALayer层 - 3D旋转

//6.设置旋转 :利用transform属性可以设置旋转
//imgView.layer.transform = CATransform3DMakeRotation(M_PI_4, 1, 1, 0);//顺时针旋转45°,在x,y轴

图像的CALayer层 - 缩放

6.设置旋转 :利用transform属性可以设置缩放
imgView.layer.transform = CATransform3DMakeScale(0.5, 1, 0);//缩小0.5倍

Add CALayer in View

UIView里有CALayer这个图层

- (void)imageLayer{
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor grayColor].CGColor;
layer.bounds = CGRectMake(0, 0, 100, 100);
layer.position = CGPointMake(200, 200);
layer.anchorPoint = CGPointMake(0, 1);
layer.cornerRadius = 10;
layer.masksToBounds = YES;
layer.contents = (id)[UIImage imageNamed:@"1.jpg"].CGImage;
layer.transform = CATransform3DMakeRotation(M_PI_4, 1, 1, 0);
[self.view.layer addSublayer:layer];
}

QuartzCore for CALayer

//导入框架 
#import <QuartzCore/QuartzCore.h>

CALayer *layer = [CALayer layer];

Position vs anchorPoint

  1. position 设置CALayer在父图层中的位置,以父层的左上角为原点(0,0)
  2. anchorPoint锚点(定位点)决定CALayer的哪个点在position属性所指的位置,以自己的左上角为原点(0,0),默认值(0.5,0.5),x~y取值是0~1,右下角(1,1)
  3. 即:哪个anchor点在position的位置

anchor point (0,0)

anchor point (1,1)

anchor point (0,1)

Customized CALayer

Method 1.

子类继承于CALayer,实现 drawInContext

JKLayer

#import "JKLayer.h"

@implementation JKLayer
-(void)drawInContext:(CGContextRef)ctx{
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
CGContextAddEllipseInRect(ctx, CGRectMake(10,10, 100, 100));
CGContextFillPath(ctx);
}
@end

ViewController

- (void)initLayer{

JKLayer *layer = [JKLayer layer];
layer.bounds = CGRectMake(0, 0, 300, 300);
layer.anchorPoint = CGPointMake(0,0);
[layer setNeedsDisplay];//必须调用这个方法,layer才会显示
[self.view.layer addSublayer:layer];
}

Method 2.

在控制器中设置代理,实现代理方法来画图层

ViewController

- (void)initLayer{

JKLayer *layer = [JKLayer layer];
layer.bounds = CGRectMake(0, 0, 300, 300);
layer.anchorPoint = CGPointMake(0,0);
layer.delegate = self;//不用协议,任何对象可以作为代理
[layer setNeedsDisplay];//必须调用这个方法,layer才会显示
[self.view.layer addSublayer:layer];

}

#pragma mark 代理方法
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
CGContextAddEllipseInRect(ctx, CGRectMake(10,10, 100, 100));
CGContextFillPath(ctx);
}