position anchorPoint

原文链接:http://blog.sina.com.cn/s/blog_155083d9e0102wi0r.html

1.确切地说,position是layer中的anchorPoint点在superLayer中的位置坐标。因此可以说, position点是相对suerLayer的,anchorPoint点是相对layer的,两者是相对不同的坐标空间的一个重合点。

  1. anchorPoint 默认值为(0.5,0.5)
    3.anchorPoint、position、frame
    anchorPoint的默认值为(0.5,0.5),也就是anchorPoint默认在layer的中心点。默认情况下,使用addSublayer函数添加layer时,如果已知layer的frame值,根据上面的结论,那么position的值便可以用下面的公式计算:
    position.x = frame.origin.x + 0.5 * bounds.size.width;
    position.y = frame.origin.y + 0.5 * bounds.size.height;

里面的0.5是因为anchorPoint取默认值,更通用的公式应该是下面的:
position.x = frame.origin.x + anchorPoint.x *
bounds.size.width;
position.y = frame.origin.y + anchorPoint.y *
bounds.size.height;

****下面再来看另外两个问题,如果单方面修改layer的position位置,会对anchorPoint有什么影响呢?修改anchorPoint又如何影响position呢?
根据代码测试,两者互不影响,受影响的只会是frame.origin,也就是layer坐标原点相对superLayer会有所改变。换句话说,frame.origin由position和anchorPoint共同决定,上面的公式可以变换成下面这样的:
frame.origin.x = position.x - anchorPoint.x *
bounds.size.width;
frame.origin.y = position.y - anchorPoint.y *
bounds.size.height;
这就解释了为什么修改anchorPoint会移动layer,因为position不受影响,只能是frame.origin做相应的改变,因而会移动layer。

因为 position点和anchorPoint点是独立的,自己不会因为另外一个的改变而发生变化,但是在实际情况中,往往有这样一种需求,我需要修改anchorPoint,但又不想要移动layer也就是不想修改frame.origin,那么根据前面的公式,就需要position做相应地修改。简单地推导,可以得到下面的公式:

positionNew.x
= positionOld.x + (anchorPointNew.x - anchorPointOld.x) *
bounds.size.width
positionNew.y = positionOld.y + (anchorPointNew.y -
anchorPointOld.y) * bounds.size.height
但是在实际使用没必要这么麻烦。修改anchorPoint而不想移动layer,在修改anchorPoint后再重新设置一遍frame就可以达到目的,这时position就会自动进行相应的改变。写成函数就是下面这样的:

  • (void)
    setAnchorPoint:(CGPoint)anchorpoint forView:(UIView *)view{
    CGRect oldFrame
    = view;
    view.layer.anchorPoint = anchorpoint;
    view.frame = oldFrame;
    }

你可能感兴趣的:(position anchorPoint)