IOS:relationship between a CALayer's position and anchorPoint properties

參考URL:http://stackoverflow.com/questions/1968017/changing-my-calayers-anchorpoint-moves-the-view


                https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/CoreAnimationBasics/CoreAnimationBasics.html#//apple_ref/doc/uid/TP40004514-CH2-SW15



           The Layer Geometry and Transforms section of the Core Animation Programming Guide explains the relationship between a CALayer's position and anchorPoint properties. Basically, the position of a layer is specified in terms of the location of the layer's anchorPoint. By default, a layer's anchorPoint is (0.5, 0.5), which lies at the center of the layer. When you set the position of the layer, you are then setting the location of the center of the layer in its superlayer's coordinate system.

Because the position is relative to the anchorPoint of the layer, changing that anchorPoint while maintaining the same position moves the layer. In order to prevent this movement, you would need to adjust the layer's position to account for the new anchorPoint. One way I've done this is to grab the layer's bounds, multiply the bounds' width and height by the old and new anchorPoint's normalized values, take the difference of the two anchorPoints, and apply that difference to the position of the layer.

You might even be able to account for rotation this way by using CGPointApplyAffineTransform()with your UIView's CGAffineTransform.


         

                  For me understanding position and anchorPoint was easiest when I started comparing it with my understanding of frame.origin in UIView. A UIView with frame.origin = (20,30) means that the UIView is 20 points from left and 30 points from top of its parent view. This distance is calculated from which point of a UIView? Its calculated from top-left corner of a UIView.

In layer anchorPoint marks the point (in normalized form i.e. 0 to 1) from where this distance is calculated so e.g. layer.position = (20, 30) means that the layer anchorPoint is 20 points from left and 30 points from top of its parent layer. By default a layer anchorPoint is (0.5, 0.5) so the distance calculation point is right in the center of the layer. The following figure will help clarify my point:

enter p_w_picpath description here

anchorPoint also happens to be the point around which rotation will happen in case you apply a transform to the layer.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章