Search code examples
swiftviewcashapelayer

Set position of outerBelowCircle CAShapeLayer in the center of View


I make a circle by using CAShapeLayer, and I want to set the center of it, in the center of the view. But the circle will be created exactly below the center line (see the screenshot), could anyone help me on this?

let circle = CAShapeLayer()
view.layer.addSublayer(circle)
circle.position = view.center


    let circularPath = UIBezierPath(arcCenter: .zero, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
    circle.path = circularPath.cgPath

I also change the way that for setting it in the center, but It doesn't work

circle.position = CGPoint(x: view.layer.bounds.midX, y: view.layer.bounds.midY)

enter image description here


Solution

  • Consider the following method according to your screenshot this method will resolve your issue.

    func showCircle() {
    
        let view = UIView()
        let circle = CAShapeLayer()
        view.layer.addSublayer(circle)
        let positionX = view.center.x
        let positionY = view.center.y - 100 // your circle radius
        circle.position = CGPoint(x: positionX, y:  positionY)
    
    
        let circularPath = UIBezierPath(arcCenter: .zero, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
        circle.path = circularPath.cgPath
    }
    

    I haven't tested the code. Please verify it by yourself.