Search code examples
iosswiftanimationcalayer

Circle isn't being drawn at the center of the view


So I am attempting to draw a circle in the center of a UIView.

class CircleView: UIView {

    let shapeLayer = CAShapeLayer()

    override func draw(_ rect: CGRect) {

        let circularPath = UIBezierPath(arcCenter: self.center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

        shapeLayer.path         = circularPath.cgPath
        shapeLayer.strokeColor  = Colors.darkPurple.cgColor
        shapeLayer.fillColor    = UIColor.white.cgColor
        shapeLayer.lineWidth    = 10
        shapeLayer.strokeEnd    = 0

        layer.addSublayer(shapeLayer)

        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
    }

    @objc private func handleTap() {
        print("....Animating Circle....")

        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        basicAnimation.toValue               = 1
        basicAnimation.duration              = 2
        basicAnimation.fillMode              = .forwards
        basicAnimation.isRemovedOnCompletion = false

        shapeLayer.add(basicAnimation, forKey: "circleAnimation")
    }
}

Yet the circle for some reason is being drawn completely at the bottom right corner of the view, even though I've specified that the arcCenter is the view's center.

enter image description here


Solution

  • Please change your centre point .. You View centre point is according to its superview .. thats why your circle was not center of your view

    let circularPath = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: bounds.midX/2, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
    

    Better to not fix the radius of your view... make it dynamic .. like i used half of the view ... its related with view size now

    Also for drawing circle use line cap to round

    shapeLayer.lineCap = .round
    

    I hope it will help you