position 和 anchorPoint

2023-02-15  本文已影响0人  一枝小王子的玫瑰花

创建一个 frame = CGRect(x: 100, y: 100, width: 100, height: 100) 的视图
打印anchorPoint 和 position

        let sublayer = CALayer()
        sublayer.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        sublayer.backgroundColor = UIColor.systemBlue.cgColor
        view.layer.addSublayer(sublayer)
        
        print(sublayer.frame)//(x: 100, y: 100, width: 100, height: 100)
        print(sublayer.anchorPoint)//锚点默认为 (0.5, 0.5)
        print(sublayer.position)//position 位置与锚点相同,展示的是在父视图中,锚点的坐标。(150.0, 150.0)

打印如下:

(100.0, 100.0, 100.0, 100.0)
(0.5, 0.5)
(150.0, 150.0)

如图:


Xnip2023-02-16_14-27-38.jpg

anchorPoint 锚点默认值为 (0.5, 0.5)
position 位置与anchorPoint 锚点相同,展示的是在父视图中,锚点的坐标。即(150.0, 150.0)

接下来,我们改变锚点的位置 = (1.0, 1.0),看看视图如何变化

        let sublayer = CALayer()
        sublayer.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        sublayer.backgroundColor = UIColor.systemBlue.cgColor
        view.layer.addSublayer(sublayer)

        sublayer.anchorPoint = CGPoint(x: 1, y: 1) //改变锚点位置
        print(sublayer.anchorPoint) // (1.0, 1.0) 锚点位置为视图右下角
        print(sublayer.position) //(150.0, 150.0) position 不变
        print(sublayer.frame) //(50.0, 50.0, 100.0, 100.0) 视图 origin 改变

打印如下:

(1.0, 1.0)
(150.0, 150.0)
(50.0, 50.0, 100.0, 100.0)

如图:

Xnip2023-02-16_14-33-20.jpg

可以看到

锚点位置为视图右下角(1.0, 1.0)
position 不变
视图 origin 改变 (50.0, 50.0, 100.0, 100.0)

再改变 position = (100,100 )看看变化

      let sublayer = CALayer()
        sublayer.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        sublayer.backgroundColor = UIColor.systemBlue.cgColor
        view.layer.addSublayer(sublayer)
        sublayer.anchorPoint = CGPoint(x: 1, y: 1) //改变锚点位置

        sublayer.position = CGPoint(x: 100, y: 100) //改变position 位置

        print(sublayer.frame) //(0.0, 0.0, 100.0, 100.0)
        print(sublayer.position)//(100.0, 100.0)
        print(sublayer.anchorPoint)//(1.0, 1.0)

打印如下:

(0.0, 0.0, 100.0, 100.0)
(1.0, 1.0)
(100.0, 100.0)

如图:


Xnip2023-02-16_14-36-34.jpg

可以看到

锚点位置为视图右下角(1.0, 1.0)
position 变为 (x: 100, y: 100)
视图 origin 改变 (50.0, 50.0, 100.0, 100.0)

上一篇下一篇

猜你喜欢

热点阅读