将贝塞尔曲线路径居中到UIview?

时间:2018-08-29 22:52:19

标签: swift animation uikit constraints uibezierpath

为了我的一生,我无法将此贝塞尔曲线路径居中(下面显示的圆圈)。橙色视图已正确约束并水平对齐,但是当我使用以下方法向橙色视图添加3层时,我似乎无法将其居中于橙色视图。我将橙色视图声明为spinnerHolder

enter image description here

private func createCircleShapeLayer(strokeColor: UIColor, fillColor: UIColor) -> CAShapeLayer {
    let layer = CAShapeLayer()

    //The farther from 0 x is for this, the more separated the movements of the 3 paths.
    let circularPath = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0),
                                    radius: 30,
                                    startAngle: 0,
                                    endAngle: 2 * CGFloat.pi,
                                    clockwise: true)
    layer.path = circularPath.cgPath
    layer.strokeColor = strokeColor.cgColor
    layer.lineWidth = 3
    layer.fillColor = fillColor.cgColor
    layer.lineCap = kCALineCapRound
    layer.position = spinnerHolder.center
    return layer
}

2 个答案:

答案 0 :(得分:2)

1-将arcCenter更改为

let circularPath = UIBezierPath(arcCenter: CGPoint(x:spinnerHolder.frame.width/2, y:spinnerHolder.frame.height/2),
                                radius: 30,
                                startAngle: 0,
                                endAngle: 2 * CGFloat.pi,
                                clockwise: true)

2-对此发表评论

layer.position = spinnerHolder.center

3-调用viewDidLayoutSubviews内的方法

var once = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once {
        spinnerHolder.addSublayer(createCircleShapeLayer(,,,,,))
        once = false
    }
}

viewDidLayoutSubviews内部进行调用不是强制性的,可以随时随地添加,但不必在VC加载之前进行

4-选中此Centering CAShapeLayer within UIView Swift

答案 1 :(得分:0)

将arcCenter点设置为

let centerPoint = CGPoint(x:self.viewRect.bounds.midX, y: self.viewRect.bounds.midY)