CALayer中anchorPoint和position的用法

来源:互联网 发布:源码投稿 编辑:程序博客网 时间:2024/05/17 07:41

每当修改一个CALayer的anchorPoint属性时,都要重新设置CALayer的position坐标

1.CALayer *layer = [myView layer];
2.[layer setAnchorPoint:CGPointMake(1.0, 1.0)];
3.[layer setPosition:CGPointMake(layer.position.x + layer.bounds.size.width * (layer.anchorPoint.x - 0.5), layer.position.y + layer.bounds.size.height * (layer.anchorPoint.y - 0.5))];

1. CALayer *layer = [myView layer];
2. CGPoint oldAnchorPoint = layer.anchorPoint;
3. [layer setAnchorPoint:CGPointMake(1.0, 1.0)];
4. [layer setPosition:CGPointMake(layer.position.x + layer.bounds.size.width * (layer.anchorPoint.x - oldAnchorPoint.x), layer.position.y + layer.bounds.size.height * (layer.anchorPoint.y - oldAnchorPoint.y))];

为什么呢?
首先要清楚,UIView的frame属性是由center和bounds属性计算得到的。
frame.origin.x = center.x - bounds.size.width/2.0;
frame.origin.y = center.y - bounds.size.height/2.0;
frame.size = bounds.size;
相对的,身为UIView下级结构的CALayer呢?
CALayer的position(相当于center),bounds,anchorPoint是什么关系呢?
虽然没有frame,但是CALayer的显示(虚拟frame)也是由这些组件算出来的
frame.origin.x = position.x - anchorPoint.x * bounds.size.width/2.0;
frame.origin.y = position.y - anchorPoint.x * bounds.size.height/2.0;
frame.size = bounds.size;
所以,当我们在上面修改anchorPoint的时候,实际上修改了显示的运算元素!这样当anchorPoint修改为(1.0,1.0)的时候,经过重新运算,CALayer向左上角移动了
0 0