圆没有绘制在视图的中心

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

所以我试图在 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")
    }
}

但是由于某种原因圆被完全绘制在视图的右下角,即使我已经指定 arcCenter 是视图的中心。

请更改你的中心点..你的视图中心点是根据它的父视图..这就是为什么你的圆不是你视图的中心

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)

最好不要固定视图的半径...让它动态化...就像我使用了一半的视图...它现在与视图大小有关

画圆也是用线帽来圆

shapeLayer.lineCap = .round

希望对你有所帮助