为什么在未在CAShapeLayer中指定中心位置的情况下,绘制的UIBezierPath位于右下角?

时间:2019-01-14 16:09:15

标签: swift calayer uibezierpath cashapelayer

我试图将UIBezierPath集中在一个超级视图中,但是UIBezierPath位于右下角,而不是中央。

我将anchorPoint的值设置为(0.5, 0.5)position self.view.centerself.view.frame.width / 2,但是UIBezierPath不在居中。

import UIKit

/* ViewSection */
class ViewController: UIViewController {
    @IBOutlet weak var Toolbar: UIToolbar!
    @IBOutlet weak var UIToolbarButtonItem: UIBarButtonItem!
    @IBAction func UIToolbarButtonItem(_ sender: Any) {
        let objectFramePath = UIBezierPath.init(roundedRect: CGRect(x: 0, y:  0, width: 150, height: 150), byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 39.5, height: 39.5))

        let shapeLayer = CAShapeLayer()
        shapeLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
        shapeLayer.position = self.view.center
        shapeLayer.fillColor = UIColor.blue.cgColor
        shapeLayer.path = objectFramePath.cgPath

        self.view.layer.addSublayer(shapeLayer)
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

结果是这样的:

screenshot of the result

1 个答案:

答案 0 :(得分:2)

锚点不起作用,因为新图层没有frame。如果您设置了它,它将起作用:

let rect = CGRect(x: 0, y:  0, width: 150, height: 150)
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 39.5, height: 39.5))

let shapeLayer = CAShapeLayer()
shapeLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
shapeLayer.frame = rect
shapeLayer.position = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.path = path.cgPath

view.layer.addSublayer(shapeLayer)

或者,您可以仅设置path的来源:

let size = CGSize(width: 150, height: 150)
let origin = CGPoint(x: view.bounds.midX - size.width / 2,
                     y: view.bounds.midY - size.height / 2)

let path = UIBezierPath(roundedRect: CGRect(origin: origin, size: size), byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 39.5, height: 39.5))

let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.path = path.cgPath

view.layer.addSublayer(shapeLayer)

顺便说一句,请注意我没有引用center,因为as the docs说:“中心点是在其父视图的坐标系中指定的。”

始终使用bounds(如果需要中心,请使用midX的{​​{1}}和midY),因为它们始终位于坐标系中有关的观点。在这种情况下,它恰好没有太大的区别,但是我们应该注意,{view}中boundsbounds的中间是两个完全不同的东西。