CAGradient 在位置为 <0 or >1

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

我正在尝试制作一个带有动画渐变颜色的标签。我可以很好地获得静态渐变。我在一个视图中玩弄动画渐变,目的是使用遮罩,但这对我们的自定义标签不满意(虽然我想我刚刚意识到为什么它不起作用......我正在考虑解决方案我目前正在研究比视图更干净)。我确实设法使用位置 [-2, -1, 0, 1] 获得了一个漂亮的无缝外观,然后动画到 [0, 1, 2, 3]。

快进到我开始创建标签的地方,它使用相同的渐变并通过以下扩展方法将该渐变设置为颜色:

extension UIColor {    
    convenience init(layer: CALayer) {
        let ctx = UIGraphicsImageRenderer(size: layer.bounds.size)
        let img = ctx.image { layer.render(in: $0.cgContext) }
        self.init(patternImage: img)
    }
}

不显示。我将它与我的静态渐变标签进行了比较,唯一的区别是我添加了位置(当然还有动画)。我决定不调用启动动画的

animate
函数,它仍然是不可见的。然后我注释掉了这个位置,突然间它变得可见了。然后,我尝试将位置放回原位并去除负值和高于 1 的值,它是可见的。然后我想知道它是否只是在动画之外它不喜欢 [0,1] 之外的数字,而在我开始动画的那一刻它又消失了。使动画中的位置在 [0,1] 内,即使这样动画也不快乐。

这是我的标签类:

class AnimatedGradientLabel: BaseLabel {
    private let startColor: UIColor = Color.gradientOrange
    private let endColor: UIColor = Color.gradientPink
    private let duration: CFTimeInterval = 4.0
    private let repeatCount: Float = Float.infinity
    var font: Font = Font.regularText

    private lazy var gradient: CAGradientLayer = {
        let gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.colors = [
//            startColor.cgColor,
//            endColor.cgColor,
            startColor.cgColor,
            endColor.cgColor
        ]

        gradientLayer.locations = [
//            -2, -1, 0, 1 // not happy
//            0, 0, 0, 1 // happy provided I don't call animate()
            0, 1 // happy provided I don't call animate()
        ] as [NSNumber]

        return gradientLayer
    }()

    override var bounds: CGRect {
        didSet {
            gradient.frame = bounds
            textColor = UIColor(layer: gradient)
        }
    }

    override func style() {
        super.style()
        font = Font.header
    }

    func animate() {
        gradient.colors = [
            endColor.cgColor,
            startColor.cgColor,
            endColor.cgColor,
            startColor.cgColor
        ]

        let anim = CABasicAnimation(keyPath: "locations")
        anim.fromValue = [-2, -1, 0, 1]
        anim.toValue = [0, 1, 2, 3]

        anim.duration = duration
        anim.repeatCount = repeatCount
        anim.fillMode = .forwards
        anim.isRemovedOnCompletion = false
        gradient.removeAllAnimations()
        gradient.add(anim, forKey: nil)
    }
}

如果有人有任何建议,我将不胜感激

编辑: 动画确实设置了只有两种颜色,并且对负数和大于 1 的数字都很满意,但我注意到它没有动画。

编辑2: 奇怪的是,它可以使用多种颜色。不完全确定我最初做错了什么。我也注意到了它没有动画的原因。 UIColor 便捷初始化器从渐变中创建了一个模式。它不按原样使用渐变。卫生署!好的,看来我可能需要回到绘图板

swift uilabel gradient cagradientlayer
© www.soinside.com 2019 - 2024. All rights reserved.