使用 CGRectMake 使椭圆居中 Swift

Centering an Oval using CGRectMake Swift

我在尝试以编程方式使我的椭圆居中时遇到问题,目前我有这段代码

    func setupLayers(){
        let oval = CAShapeLayer()
        oval.frame = CGRectMake(137.5, 283.5, 100, 100)
        oval.path = ovalPath().CGPath;
        self.layer.addSublayer(oval)
        layers["oval"] = oval

        resetLayerPropertiesForLayerIdentifiers(nil)
    }

此代码能够在 iPhone 6 和 6s 中将椭圆居中,但我希望它能够在所有设备中居中。

我也试过这段代码:

    func drawCircle(size: CGFloat) {
let circleShape = CAShapeLayer()
circleShape.path = UIBezierPath(ovalInRect: CGRectMake(-size/2, -size/2, size, size)).CGPath
circleShape.fillColor = UIColor.blueColor().CGColor
circleShape.strokeColor = UIColor.redColor().CGColor
circleShape.lineWidth = 1
circleShape.frame.origin = view.center
circleShape.name = "circleShape"
view.layer.addSublayer(circleShape)

}

画圆(100)

您需要将图层的锚点设置为其中心。

oval.anchorPoint = CGPoint(x: 0.5, y: 0.5)

然后可以设置图层位置为视图中心:

oval.position = self.center