圆圈没有画在视图的中心位置。

问题描述 投票:1回答:1

所以我试图在一个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是视图的中心。

enter image description here

ios swift animation calayer
1个回答
0
投票

请改变你的中心点......你的视图中心点是根据它的上层视图......这就是为什么你的圆圈不是你的视图的中心点

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

希望对你有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.