gpt4 book ai didi

swift - 更改 donut View 周围的颜色渐变

转载 作者:行者123 更新时间:2023-11-28 07:31:51 25 4
gpt4 key购买 nike

我正在尝试制作一个动画 donut View ,当给定一个介于 0 和 100 之间的值时,它会将 View 动画化到该数字。我有这个工作正常,但想要将颜色从一种颜色淡化到另一种颜色,然后再逐渐淡化另一种颜色。目前,当我添加渐变时,它是从左到右而不是围绕 donut View 的圆周。

    class CircleScoreView: UIView {
private let outerCircleLayer = CAShapeLayer()
private let outerCircleGradientLayer = CAGradientLayer()
private let outerCircleLineWidth: CGFloat = 5

override init(frame: CGRect) {
super.init(frame: .zero)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func layoutSubviews() {
super.layoutSubviews()
buildLayers()
}

/// Value must be within 0...100 range
func setScore(_ value: Int, animated: Bool = false) {
if value != 0 {
let clampedValue: CGFloat = CGFloat(value.clamped(to: 0...100)) / 100
if !animated {
outerCircleLayer.strokeEnd = clampedValue
} else {
let outerCircleAnimation = CABasicAnimation(keyPath: "strokeEnd")
outerCircleAnimation.duration = 1.0
outerCircleAnimation.fromValue = 0
outerCircleAnimation.toValue = clampedValue
outerCircleAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

outerCircleLayer.strokeEnd = clampedValue
outerCircleLayer.add(outerCircleAnimation, forKey: "outerCircleAnimation")
}

outerCircleGradientLayer.colors = [Constant.Palette.CircleScoreView.startValue.cgColor,
Constant.Palette.CircleScoreView.middleValue.cgColor,
Constant.Palette.CircleScoreView.endValue.cgColor]
}
}

private func buildLayers() {

// Outer background circle
let arcCenter = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
let startAngle = CGFloat(-0.5 * Double.pi)
let endAngle = CGFloat(1.5 * Double.pi)

let circlePath = UIBezierPath(arcCenter: arcCenter,
radius: (frame.size.width - outerCircleLineWidth) / 2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)

// Outer circle
setupOuterCircle(outerCirclePath: circlePath)
}

private func setupOuterCircle(outerCirclePath: UIBezierPath) {
outerCircleLayer.path = outerCirclePath.cgPath
outerCircleLayer.fillColor = UIColor.clear.cgColor
outerCircleLayer.strokeColor = UIColor.black.cgColor
outerCircleLayer.lineWidth = outerCircleLineWidth
outerCircleLayer.lineCap = CAShapeLayerLineCap.round

outerCircleGradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
outerCircleGradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
outerCircleGradientLayer.frame = bounds
outerCircleGradientLayer.mask = outerCircleLayer
layer.addSublayer(outerCircleGradientLayer)
}
}

我想要类似 this 的东西但颜色不是一个 block ,而是围绕 donut View 从一种颜色到另一种颜色的渐变。

最佳答案

如果您导入了 AngleGradientLayer到你的项目中,那么你需要做的就是改变:
private let outerCircleGradientLayer = CAGradientLayer()
private let outerCircleGradientLayer = AngleGradientLayer()

关于swift - 更改 donut View 周围的颜色渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54491718/

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