iOS:CALayer锚点的使用

CALayer层的位置主要和position和anchorPoint有关。其中它们在一起才能决定层在视图中的具体位置。

@property CGPoint position;         //位置

@property CGPoint anchorPoint;  //锚点

锚点的范围:(0.0~1.0)

具体的演示如下:

1、采用默认的锚点(0.5,0.5)

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //添加子层
    CALayer *subLayer = [[CALayer alloc]init];
    
    //层的大小用bounds设置
    subLayer.bounds = CGRectMake(0, 0, 100, 100);
    subLayer.backgroundColor = [[UIColor redColor]CGColor];
    
    //层的位置是靠position和anchorPoint共同确定的
    subLayer.position = CGPointMake(100, 100);
    [self.view.layer addSublayer:subLayer];
}

演示结果:anchorPoint锚点在红色矩形的中心处


 

 

2、采用自定义的锚点(0.0,0.0)

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //添加子层
    CALayer *subLayer = [[CALayer alloc]init];
    
    //层的大小用bounds设置
    subLayer.bounds = CGRectMake(0, 0, 100, 100);
    subLayer.backgroundColor = [[UIColor redColor]CGColor];
    
    //层的位置是靠position和anchorPoint共同确定的
    subLayer.position = CGPointMake(100, 100);
    
    
    //默认的锚点(0.5,0.5)
    //subLayer.anchorPoint = CGPointMake(0, 0);
    
    
    [self.view.layer addSublayer:subLayer];
}

演示结果:anchorPoint锚点在红色矩形的左上角转角这一点处

 

3、采用自定义的锚点(0.0,0.5)

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //添加子层
    CALayer *subLayer = [[CALayer alloc]init];
    
    //层的大小用bounds设置
    subLayer.bounds = CGRectMake(0, 0, 100, 100);
    subLayer.backgroundColor = [[UIColor redColor]CGColor];
    
    //层的位置是靠position和anchorPoint共同确定的
    subLayer.position = CGPointMake(100, 100);
    
    
    //默认的锚点(0.5,0.5)
    subLayer.anchorPoint = CGPointMake(0, 0.5);
    
    
    [self.view.layer addSublayer:subLayer];
}

演示结果:anchorPoint锚点在红色矩形的上面一条边的中心处

 

 

4、采用自定义的锚点(0.5,0.0)

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //添加子层
    CALayer *subLayer = [[CALayer alloc]init];
    
    //层的大小用bounds设置
    subLayer.bounds = CGRectMake(0, 0, 100, 100);
    subLayer.backgroundColor = [[UIColor redColor]CGColor];
    
    //层的位置是靠position和anchorPoint共同确定的
    subLayer.position = CGPointMake(100, 100);
    
    
    //默认的锚点(0.5,0.5)
    subLayer.anchorPoint = CGPointMake(0.5, 0);
    
    
    [self.view.layer addSublayer:subLayer];
}

演示结果:anchorPoint锚点在红色矩形的左边一条边的中心处

 

总结:

可以看出,层的位置光凭position是无法确定的,每一次anchorPoint锚点的不同,层的位置也就发生的了改变。所以,层的位置是有position和anchorPoint锚点共同决定的。

posted @ 2015-10-15 13:58  XYQ全哥  阅读(724)  评论(0编辑  收藏  举报