一.position和anchorPoint 
1.简单介绍 
CALayer有2个非常重要的属性:position和anchorPoint 
  position: 
  (1)用来设置CALayer在父层中的位置 
  (2)以父层的左上角为原点(0,0) 
anchorPoint: 
  (1)称为”定位点”,”锚点” 
  (2)决定着CALayer身上的哪个点会在position属性所指的位置 
  (3)以自己的左上角为原点(0,0) 
  (4)它的x,y取值范围都是0~1,默认值为(0.5,0.5)

2.图示 
  anchorPoint 它的取值为0~1

CALayer层的属性(转)-LMLPHP

红色图层的anchorPoint为(0,0)

CALayer层的属性(转)-LMLPHP

红色图层的anchorPoint为(0.5,0.5)

CALayer层的属性(转)-LMLPHP

红色图层的anchorPoint为(1,1)

CALayer层的属性(转)-LMLPHP

红色图层的anchorPoint为(0.5,0)

CALayer层的属性(转)-LMLPHP

position和anchorPoint 
添加一个红色图层到绿色图层上,红色图层显示到什么位置,由position属性决定 
假设红色图层的position是(100,100) 
到底把红色图层的哪个点移动到(100,100)的坐标位置,锚点。 
红色图层的锚点是(0,0)

CALayer层的属性(转)-LMLPHP

红色图层的锚点是(0.5,0.5)

CALayer层的属性(转)-LMLPHP

红色图层的锚点是(1,1)

CALayer层的属性(转)-LMLPHP

红色图层的锚点是(0.5,0)

CALayer层的属性(转)-LMLPHP

3.代码示例 
(1)没有设置锚点。默认的锚点位置为(0.5,0.5)

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
//创建图层
CALayer *layer = [CALayer layer];
//设置图层的属性
layer.backgroundColor = [UIColor redColor].CGColor;
layer.bounds = CGRectMake(, , , );
//添加图层
[self.view.layer addSublayer:layer];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

(2)设置锚点为(0,0)

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
//创建图层
CALayer *layer = [CALayer layer];
//设置图层的属性
layer.backgroundColor = [UIColor redColor].CGColor;
layer.bounds = CGRectMake(, , , );
//设置锚点为(0,0)
layer.anchorPoint = CGPointZero;
//添加图层
[self.view.layer addSublayer:layer];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

二.隐式动画 

1.简单说明 
  每一个UIView内部都默认关联着一个CALayer,我们称这个Layer为Root Layer(根层)。 所有的非Root Layer,也就是手动创建的CALayer对象,都存在着隐式动画 
  什么是隐式动画? 当对非Root Layer的部分属性进行修改时,默认会自动产生一些动画效果。 而这些属性称为Animatable Properties(可动画属性)。 

举例几个常见的可动画属性 
  (1)bounds:用于设置CALayer的宽度和高度。修改这个属性会产生缩放动画 
  (2)backgroudColor:用于设置CALayer的背景色。修改这个属性会产生背景色的渐变动画。 
  (3)position:用于设置CALayer的位置。修改这个属性会产生平移动画。 
2.代码示例

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
//创建图层
CALayer *layer = [CALayer layer];
//设置图层属性
layer.backgroundColor = [UIColor brownColor].CGColor;
layer.bounds = CGRectMake(, , , );
//显示位置
layer.position = CGPointMake(, );
layer.anchorPoint = CGPointZero;
layer.cornerRadius = ;
//添加图层
[self.view.layer addSublayer:layer];
_myLayer = layer;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//隐式动画
_myLayer.bounds = CGRectMake(, , , );
_myLayer.backgroundColor = [UIColor yellowColor].CGColor;
} @end

关闭隐式动画

 //关闭隐式动画
[CATransaction begin];
[CATransaction setDisableActions:YES];
//隐式动画
_myLayer.bounds = CGRectMake(, , , );
_myLayer.backgroundColor = [UIColor yellowColor].CGColor;
[CATransaction commit];
05-11 00:38