iOS循环渐变

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

我有一个任务是用圆形渐变绘制线条(颜色应该由圆圈改变),然后添加动画。现在我用一定的间隔和不同的颜色绘制360层。

var colours: [UIColor] = [UIColor]()
var startAngle = CGFloat(-0.5 * Double.pi)
var index = 0

func drawLayers() {
    let smallAngle = (1.5 * CGFloat.pi - (-0.5 * CGFloat.pi)) / 360

    if index < colours.count { //colours.count = 360
        let endAngle = startAngle + smallAngle
        let circlePath = UIBezierPath(arcCenter: .init(x: 100, y: 100), radius: 100, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        startAngle = endAngle
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath

        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = colours[index].cgColor
        shapeLayer.lineWidth = 8

        view.layer.addSublayer(shapeLayer)

        index += 1

        Timer.scheduledTimer(
            withTimeInterval: 0.004,
            repeats: false) { (_) in
                self.drawLayers()
        }
    }
}

类似的东西,但有线性动画

enter image description here

谁能告诉我怎么做对了?

ios swift
1个回答
5
投票

iOS现在内置了圆形(圆锥形)渐变。所以我只想要一次渐变,然后为用作蒙版的单个路径设置动画。这只是两层,更少的工作,真正的动画和真正的渐变。

例:

enter image description here

这是我的测试代码;根据需要更改颜色和数字:

    let grad = CAGradientLayer()
    grad.type = .conic
    grad.colors = [UIColor.red.cgColor, UIColor.green.cgColor, UIColor.red.cgColor]
    grad.startPoint = CGPoint(x: 0.5, y: 0.5)
    grad.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
    self.view.layer.addSublayer(grad)
    let c = CAShapeLayer()
    let p = UIBezierPath(ovalIn: CGRect(x: 20, y: 20, width: 160, height: 160))
    c.path = p.cgPath
    c.fillColor = UIColor.clear.cgColor
    c.strokeColor = UIColor.black.cgColor
    c.lineWidth = 8
    grad.mask = c
    c.strokeEnd = 0

要制作动画,只需说:

    c.strokeEnd = 1
© www.soinside.com 2019 - 2024. All rights reserved.