gpt4 book ai didi

iOS 圆形渐变

转载 作者:可可西里 更新时间:2023-11-01 00:28:59 25 4
gpt4 key购买 nike

我有一个任务是绘制带有圆形渐变的线条(颜色应随圆圈变化),然后添加动画。现在我以一定的间隔和不同的颜色绘制 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 现在内置了圆形(圆锥形)渐变。所以我只要求一次渐变,然后为用作 mask 的单个路径设置动画。这只是两层,工作量少得多,真正的动画和真正的渐变。

例子:

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

关于iOS 圆形渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53934686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com