UILayer的anchorPoint和position详解

相信初接触到CALayer的人都会遇到以下几个问题: 为什么修改anchorPoint会移动layer的位置? CALayer的position点是哪一点呢? anchorPoint与position有什么关系?
每一个UIView都默认关联着一个CALayer, UIView有frame、bounds和center三个属性,CALayer也有类似的属性,分别为frame、bounds、position、anchorPoint。那position、anchorPoint是什么呢?先看看两者的原型,可知都是CGPoint点。

@property CGPoint position ;
@property CGPoint anchorPoint ;
anchorPoint (锚点)

从一个例子开始入手吧,想象一下,把一张A4白纸用图钉订在书桌上,如果订得不是很紧的话,白纸就可以沿顺时针或逆时针方向围绕图钉旋转,这时候图钉就起着支点的作用。我们要解释的anchorPoint就相当于白纸上的图钉,它主要的作用就是用来作为变换的支点,旋转就是一种变换,类似的还有平移、缩放。

继续扩展,很明显,白纸的旋转形态随图钉的位置不同而不同,图钉订在白纸的正中间与左上角时分别造就了两种旋转形态,这是由图钉(anchorPoint)的位置决定的。如何衡量图钉(anchorPoint)在白纸中的位置呢?在iOS中,anchorPoint点的值是用一种相对bounds的比例值来确定的,在白纸的左上角、右下角,anchorPoint分为为(0,0), (1, 1),也就是说anchorPoint是在单元坐标空间(同时也是左手坐标系)中定义的。类似地,可以得出在白纸的中心点、左下角和右上角的anchorPoint为(0.5,0.5), (0,1), (1,0)。

  1. anchorPoint = CGPointMake(0.5, 0.5)


    UILayer的anchorPoint和position详解_第1张图片
    006fd7UGgy6Yub8vPg65a&690.png
  2. anchorPoint = CGPointMake(0.0, 0.0);

UILayer的anchorPoint和position详解_第2张图片
006fd7UGgy6Yub9TfU8cc&690.png

然后执行旋转同样角度后的结果:

UILayer的anchorPoint和position详解_第3张图片
006fd7UGgy6YubcDMc353&690.png
UILayer的anchorPoint和position详解_第4张图片
006fd7UGgy6YubdIiNmcc&690.png
position

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

再来看看position的原始定义: The layer’s position in its superlayer’s coordinate space。 中文可以理解成为position是layer相对superLayer坐标空间的位置,很显然,这里的位置是根据anchorPoint来确定的.

你可能感兴趣的:(UILayer的anchorPoint和position详解)