我试图将UIBezierPath
集中在一个超级视图中,但是UIBezierPath
位于右下角,而不是中央。
我将anchorPoint
的值设置为(0.5, 0.5)
,position
self.view.center
或self.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.
}
}
结果是这样的:
答案 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}中bounds
和bounds
的中间是两个完全不同的东西。