切换颜色动画

最初的想法

两个UIView直接切换,上代码

let aView = UIView()
let bView = UIView()

aView.frame = CGRect(x: 100, y: 300, width: 100, height: 100)
aView.alpha = 1
aView.backgroundColor = .red
view.addSubview(aView)

bView.frame = CGRect(x: 100, y: 300, width: 100, height: 100)
bView.alpha = 0
bView.backgroundColor = .orange
view.addSubview(bView)

func switchView(type: Int) {
    if type == 0 {
        UIView.animate(withDuration: 0.3) {
            self.aView.alpha = 0
            self.bView.alpha = 1
        } completion: { finished in
            if finished {
                self.aView.alpha = 0
                self.bView.alpha = 1
            }
        }
    } else {
        UIView.animate(withDuration: 0.3) {
            self.aView.alpha = 1
            self.bView.alpha = 0
        } completion: { finished in
            if finished {
                self.aView.alpha = 1
                self.bView.alpha = 0
            }
        }
    }
}

但是效果不是很如意,有些闪动

修改之后的方案

通过两个CALayer做动画,当然如果是渐变,用CAGradientLayer也可以

let tView = UIView()
let layer = CALayer()

tView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
view.addSubview(tView)

layer.frame = tView.bounds
layer.backgroundColor = UIColor.red.cgColor
tView.layer.addSublayer(layer)

func switchView(type: Int) {
let duration: CFTimeInterval = 0.3
let colorChangeAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorChangeAnimation.duration = duration
colorChangeAnimation.fillMode = .forwards
colorChangeAnimation.isRemovedOnCompletion = false
if type == 0 { colorChangeAnimation.toValue = UIColor.orange.cgColor layer.removeAnimation(forKey: "colorChangeAnimationa") layer.add(colorChangeAnimation, forKey: "colorChangeAnimationa") } else { colorChangeAnimation.toValue = UIColor.red.cgColor layer.removeAnimation(forKey: "colorChangeAnimationb") layer.add(colorChangeAnimation, forKey: "colorChangeAnimationb") } }

两种方案对比视频

能看出来下面比闪动厉害

总结

用CALayer做动画效果更好。如果只是单纯改变背景色,用下面代码实现更加方便

let gView = UIView()

gView.frame = CGRect(x: 100, y: 500, width: 100, height: 100)
gView.backgroundColor = .red
view.addSubview(gView)

func changeColor(color: UIColor) {
    UIView.animate(withDuration: 3) {
        self.gView.backgroundColor = color
    }
}

 

posted @ 2023-07-08 10:07  夏风已过  阅读(19)  评论(0)    收藏  举报