实现按钮的动画效果

2016-12-30  本文已影响312人  yytester

原文链接 ----- sindrilin


在iOS中,每一个UIView都拥有一个与之绑定的CALayer图层对象,其负责视图内容的绘制与显示。
跟前者一样,CALayer也拥有树状的子图层结构,以及相似的接口方法。CALayer是图层的基类,主要提供了视图显示范围、图层结构接口等属性,我们通过使用它的子类。

在控制器的界面中心添加一个圆形的紫色图层:

    let layer = CAShapeLayer()
  
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.layer.fillColor = UIColor.purple.cgColor
        self.layer.path = UIBezierPath(arcCenter: CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2), radius: 100, startAngle: 0, endAngle: 2.0*CGFloat(M_PI), clockwise: false).cgPath
        self.view.layer.addSublayer(layer)
        
    }

基础动画


基础动画CABasicAnimation是最常用来实现动画效果的动画类,其继承自CAAnimation动画基类,为图层动画效果实现了一个keyPath属性,我们通过设置这个属性来为对应的keyPath属性值执行动画效果。动画类提供了fromValue和toValue两个属性用来设置动画的起始和结束的值,比如下面一段代码让添加到视图上的紫色图层变得透明:

        let animation = CABasicAnimation(keyPath: "opacity")
        animation.fromValue = NSNumber(value: 1)
        animation.toValue = NSNumber(value: 0)
        animation.duration = 1
        self.layer.add(animation, forKey: nil)

在每一个CALayer中存在着模型、呈现、渲染三种图层树,正是这些图层树共同作用来完成隐式动画。那么使用核心动画的时候,实际上CABasicAnimation会根据动画时长计算出每一帧的动画属性的值,然后实时提交给呈现树来展示对应时间点的视图效果,在动画结束时CAAnimation对象会自动从图层上移除。而由于在整个动画过程模型树的值没有改变,所以在动画结束的时候呈现树会再次从模型树获取图层的属性重新绘制。

解决方式: 取消CAAnimation的自动移除,并且设置在动画结束后保持动画的结束状态

        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false

扩展之后的按钮只要设置animationType这个属性之后就会实现在点击时的动画效果.

完整代码:


import UIKit




class ViewController: UIViewController {

    @IBOutlet weak var uiButtonName: UIButton!
    
    let layer = CAShapeLayer()
  
    override func viewDidLoad() {
        super.viewDidLoad()
    
        
        uiButtonName.animationType = .Outer
        layer.frame = UIScreen.main.bounds
        self.layer.fillColor = UIColor.purple.cgColor
        self.layer.path = UIBezierPath(arcCenter: CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2), radius: 100, startAngle: 0, endAngle: 2.0*CGFloat(M_PI), clockwise: false).cgPath

        self.view.layer.addSublayer(layer)
        
    }
    
 
    
    @IBAction func onclick(_ sender: Any) {
        
        
        let opacity = CABasicAnimation(keyPath: "opacity")
        opacity.fromValue = NSNumber(value: 1)
        opacity.toValue = NSNumber(value: 0)
       // opacity.duration = 1
        
        layer.add(opacity, forKey: "opacity")
        
        let scale = CABasicAnimation(keyPath: "transform")
        scale.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
        scale.toValue = NSValue(caTransform3D: CATransform3DMakeScale(2, 2, 2))
     //   scale.duration = 1
 
        
        let group = CAAnimationGroup()
        group.animations = [opacity, scale]
        group.duration = 5
        layer.add(group, forKey: "group")

        
    }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if anim is CABasicAnimation {
            let animation = anim as! CABasicAnimation
            if let layer = animation.value(forKey: "animatedLayer") as? CALayer {
                layer.setValue(animation.toValue, forKey: animation.keyPath!)
                layer.removeAllAnimations()
            }
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    


}


private var kAnimationTypeKey: UInt = 0
private var kAnimationColorKey: UInt = 1

//扩展按钮功能,扩展之后的按钮只要设置animationType这个属性之后就会实现在点击时的动画效果
extension UIButton {
    
    enum LXDAnimationType : String {
        case Inner //动画内扩
        case Outer //动画外扩
    }
    
    //动画类型
    var animationType: LXDAnimationType? {
        get {
            if let type = (objc_getAssociatedObject(self, &kAnimationTypeKey) as? String) {
                return LXDAnimationType(rawValue: type)
            }
            return nil
        }
        set {
            guard newValue != nil else { return }
            self.clipsToBounds = (newValue == .Inner)
            objc_setAssociatedObject(self, &kAnimationTypeKey, newValue!.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    //动画颜色
    var animationColor: UIColor {
        get {
            if let color = objc_getAssociatedObject(self, &kAnimationColorKey) {
                return color as! UIColor
            }
            return UIColor.white
        }
        set {
            objc_setAssociatedObject(self, &kAnimationColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    //重写按钮的sendAction方法来执行动画,这个方法在每次按钮发送一个事件时会被调用.
    open override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
        
        super.sendAction(action, to: target, for: event)
        
        if let type = animationType {
            var rect: CGRect?
            var radius = self.layer.cornerRadius
            
            var pos = touchPoint(event: event)
            let smallerSize = min(self.frame.width, self.frame.height)
            let longgerSize = max(self.frame.width, self.frame.height)
            var scale = longgerSize / smallerSize + 0.5
            
            switch type {
            case .Inner:
                radius = smallerSize / 2
                rect = CGRect(x: 0, y: 0, width: radius*2, height: radius*2)
                break
                
            case .Outer:
                scale = 2.5
                pos = CGPoint(x: self.bounds.width/2, y: self.bounds.height/2)
                rect = CGRect(x: pos.x - self.bounds.width, y: pos.y - self.bounds.height, width: self.bounds.width, height: self.bounds.height)
                break
            }
            
            let layer = animateLayer(rect: rect!, radius: radius, position: pos)
            let group = animateGroup(scale)
            self.layer.addSublayer(layer)
            group.setValue(layer, forKey: "animatedLayer")
            layer.add(group, forKey: "buttonAnimation")
        }
    }
    
    public  func animationDidStop(anim: CAAnimation, finished flag: Bool) {
        if let layer = anim.value(forKey: "animatedLayer") as? CALayer {
            layer .removeFromSuperlayer()
        }
    }
    
    
    //MARK: - Private
    private func touchPoint(event: UIEvent?) -> CGPoint {
        if let touch = event?.allTouches?.first {
            return touch.location(in: self)
        } else {
            return CGPoint(x: self.frame.width/2, y: self.frame.height/2)
        }
    }
    
    private func animateLayer(rect: CGRect, radius: CGFloat, position: CGPoint) -> CALayer {
        let layer = CAShapeLayer()
        layer.lineWidth = 1
        layer.position = position
        layer.path = UIBezierPath(roundedRect: rect, cornerRadius: radius).cgPath
        
        switch animationType! {
        case .Inner:
            layer.fillColor = animationColor.cgColor
            layer.bounds = CGRect(x: 0, y: 0, width: radius*2, height: radius*2)
            break
            
        case .Outer:
            layer.strokeColor = animationColor.cgColor
            layer.fillColor = UIColor.clear.cgColor
            break
        }
        return layer
    }
    
    
    fileprivate func animateGroup(_ scale: CGFloat) -> CAAnimationGroup {
        let opacityAnim = CABasicAnimation(keyPath: "opacity")
        opacityAnim.fromValue = NSNumber(value: 1 as Double)
        opacityAnim.toValue = NSNumber(value: 0 as Double)
        
        let scaleAnim = CABasicAnimation(keyPath: "transform")
        scaleAnim.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
        scaleAnim.toValue = NSValue(caTransform3D: CATransform3DMakeScale(scale, scale, scale))
        
        let group = CAAnimationGroup()
        group.animations = [opacityAnim, scaleAnim]
        group.duration = 0.5
      //  group.delegate = self.animationDidStop(anim: <#T##CAAnimation#>, finished: <#T##Bool#>)
        group.fillMode = kCAFillModeBoth
        group.isRemovedOnCompletion = false
        return group
    }
   
    
}





上一篇下一篇

猜你喜欢

热点阅读