制作更清晰的CAGradientLayer动画

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

我在 tableView 单元格中创建了一个闪光效果动画,并使用以下设置来显示动画:

func startShimmerAnimation() {
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

    gradientLayer.colors = [
        UIColor.systemGray5.cgColor,
        UIColor.white.cgColor,
        UIColor.systemGray5.cgColor
    ]

    gradientLayer.locations = [0.4, 0.5, 0.6]
    gradientLayer.cornerRadius = 10
    
    let animation = CABasicAnimation(keyPath: "locations")
    animation.fromValue = [-1.0, -0.5, 0.0]
    animation.toValue = [1.0, 1.5, 2.0]
    animation.repeatCount = .infinity
    animation.duration = 1.0
    animation.repeatCount = 1
    animation.fillMode = .forwards
    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
    
    let group = CAAnimationGroup()
    group.animations = [animation]
    group.duration = 2.0
    group.repeatCount = .infinity
    
    gradientLayer.add(group, forKey: "shimmer")
}

但是请看一下 gif。闪光后会出现明显的灰色实心区域,看起来不整洁。

如何删除该区域,以便在白色闪光后没有任何明显的区域跟随它?

swift animation uikit cagradientlayer
1个回答
0
投票

我不清楚你到底想创造什么效果,因为你的数字彼此不一致。但这种不一致正是问题的根源。这一行:

    gradientLayer.locations = [0.4, 0.5, 0.6]

建议您希望渐变的白色部分从宽度的 4/10 延伸到宽度的 6/10:

但这不是你的动画所说的。考虑一下你的

fromValue

animation.fromValue = [-1.0, -0.5, 0.0]

如果我们可以看到该渐变(我们看不到,因为它位于视图的左侧),它将如下所示:

让我们通过使您的

fromValue
toValue
与您的
locations
匹配来消除这种不匹配,只需在每个方向上将它们偏移
1
即可:

    animation.fromValue = [-0.6, -0.5, -0.4]
    animation.toValue = [1.4, 1.5, 1.6]

结果可能不完全是您想要的,但它不会突然变成灰色,因为在屏幕上移动的闪烁渐变与渐变位置的实际位置相匹配:

© www.soinside.com 2019 - 2024. All rights reserved.