切换颜色动画

最初的想法

两个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 @   夏风已过  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示