iOS-position与anchorPoint

UIView在布局中最常用的三个属性是frame、bounds和center,CALayer也有类似的属性,分别为frame、bounds、position、anchorPoint.

Position

    /* The position in the superlayer that the anchor point of the layer's
     * bounds rect is aligned to. Defaults to the zero point. Animatable. */

通过position定义可以知道position是layer中的anchorPoint点在superLayer中的位置坐标.position点是相对superLayer的.

AnchorPoint

    /* Defines the anchor point of the layer's bounds rect, as a point in
     * normalized layer coordinates - '(0, 0)' is the bottom left corner of
     * the bounds rect, '(1, 1)' is the top right corner. Defaults to
     * '(0.5, 0.5)', i.e. the center of the bounds rect. Animatable. */

anchorPoint是相对于自身layer,anchorPoint点(锚点)的值是用相对bounds的比例值来确定的,iOS坐标系中(0,0), (1,1)分别表示左上角、右下角.

iOS-position与anchorPoint_第1张图片
FlyElephant.png

anchorPoint相当于支点,可以用作旋转变化、平移、缩放.

如果修改anchorPoint则layer的frame会发生改变,position不会发生改变.修改position与anchorPoint中任何一个属性都不影响另一个属性.

原始视图:

      let bgView:UIView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
        bgView.backgroundColor = UIColor.red
        self.view.addSubview(bgView)
        
        let midView:UIView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
        midView.backgroundColor = UIColor.blue
        bgView.addSubview(midView)
        
        print("FlyElephant---中间视图的frame:\(midView.layer.frame)")
        print("FlyElephant---中间视图的position:\(midView.layer.position)")
        print("FlyElephant---中间视图的anchorPoint:\(midView.layer.anchorPoint)")

修改锚点:

       let bgView:UIView = UIView(frame: CGRect(x: 100, y: 400, width: 200, height: 200))
        bgView.backgroundColor = UIColor.red
        self.view.addSubview(bgView)
        
        let midView:UIView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
        midView.backgroundColor = UIColor.blue
        midView.layer.anchorPoint = CGPoint(x: 1, y: 1)
        bgView.addSubview(midView)
        
        print("anchorPoint---中间视图的frame:\(midView.layer.frame)")
        print("anchorPoint---中间视图的position:\(midView.layer.position)")
        print("anchorPoint---中间视图的anchorPoint:\(midView.layer.anchorPoint)")

视图位置计算公式:

frame.origin.x = position.x - anchorPoint.x * bounds.size.width;  
frame.origin.y = position.y - anchorPoint.y * bounds.size.height;
FlyElephant.png

如果修改anchorPoint之后不想让视图位置发生改变,那么可以在修改锚点之后重新对frame赋值.
参考资料:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreAnimation_guide/CoreAnimationBasics/CoreAnimationBasics.html#//apple_ref/doc/uid/TP40004514-CH2-SW15

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