1

I am having trouble trying to center my oval programmatically currently I have this code

    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)
    }

This code is able to center the oval in an iPhone 6 and 6s, but I want it to be able to be centered in all devices.

I have tried this code too:

    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)

Harish
  • 1,374
  • 17
  • 39

1 Answers1

1

You need to set the layer's anchorPoint to be its center.

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

Then you can set position of layer as the center of view:

oval.position = self.center
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • Thanks for the quick reply, I tried to implement that code, but for some reason it is still not centering the oval. It is still coming off to the side. – Harish Nov 01 '15 at 14:43