【问题标题】:Centering an Oval using CGRectMake Swift使用 CGRectMake Swift 使椭圆居中
【发布时间】:2015-11-01 01:46:41
【问题描述】:

我无法以编程方式将我的椭圆居中,目前我有此代码

    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)

}

drawCircle(100)

【问题讨论】:

    标签: ios swift constraints cgrectmake


    【解决方案1】:

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

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

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

    oval.position = self.center
    

    【讨论】:

    • 感谢您的快速回复,我尝试实现该代码,但由于某种原因,它仍未使椭圆居中。它仍然偏向一边。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多