Swift兴趣开发到爱上开发Swift编程

简单的CABasicAnimation动画

2018-06-22  本文已影响93人  让代码飞

实现的简单的动画效果平时仅仅的是用uiview动画就满足了,很少接触到CABasicAnimation,但是最近突然想简单的了解一下

image.png

写了一个长按动画打卡成功的效果,下边是效果图

小动画.gif
       这里是创建的方法
        button.frame = CGRect.init(x: (self.view.frame.size.width-100)/2, y: 100, width: 100, height: 100)
        button.backgroundColor = UIColor.red
        button.layer.cornerRadius = 50
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(TapAction), for: .touchDown)
        button.addTarget(self, action: #selector(touchUp), for: .touchUpInside)
        button.setTitle("下班打卡", for: .normal)
        button.titleLabel?.textAlignment = NSTextAlignment.center
        button.setTitleColor(UIColor.black, for: .normal)
        self.view.addSubview(button)
        
        let cGpath = UIBezierPath.init(ovalIn:button.frame)
        cGpath.fill()
        myLayer.fillColor = UIColor.clear.cgColor
        myLayer.path = cGpath.cgPath
        myLayer.strokeColor = UIColor.clear.cgColor
        myLayer.lineWidth = 8
        myLayer.lineCap = kCALineCapRound
        self.view.layer.addSublayer(myLayer)
//动画结束的代理
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag {
            button.setTitle("打卡成功", for: .normal)
        }else{
            button.setTitle("下班打卡", for: .normal)
        }
    }
    //长按时候触发
    @objc func TapAction () {
        myLayer.strokeColor = UIColor.yellow.cgColor
        let animation = CABasicAnimation.init(keyPath: "strokeEnd")
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = 2.0
        animation.delegate = self
        myLayer.strokeEnd = 1
        myLayer.add(animation, forKey: "clockOff")
    }
    //点击触发
    @objc func touchUp() {
        if myLayer.animation(forKey: "clockOff") != nil {
            myLayer.strokeColor = UIColor.clear.cgColor
            myLayer.strokeEnd = 0
            myLayer.removeAnimation(forKey: "clockOff")
        }
    }

上一篇下一篇

猜你喜欢

热点阅读