iOS-position与anchorPoint

作者: FlyElephant | 来源:发表于2017-06-01 07:22 被阅读651次

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

Position

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

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

AnchorPoint

<pre><code>/* 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. */</code></pre>

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

FlyElephant.png

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

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

原始视图:
<pre><code>` 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)")`</code></pre>

修改锚点:
<pre><code>` 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)")`</code></pre>

视图位置计算公式:
<pre><code>frame.origin.x = position.x - anchorPoint.x * bounds.size.width; frame.origin.y = position.y - anchorPoint.y * bounds.size.height;</code></pre>

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

    本文链接:https://www.haomeiwen.com/subject/nslrfxtx.html