2018正版葡京赌侠诗iOS动画-按钮动画

前言

在上一篇认识CoreAnimation中笔者介绍了系统的动画库CoreAnimation,使用动画库有成百上千好处,这里就不再进行再一次叙述。那么本篇将承载上一篇的始末,使用提到的根基的动画相关类来促成动画效果,效果图放上:

大体上可以看看demo重假诺渐变以及形变二种动画,在更早在此以前的随笔,大家就使用UIView的动画接口完成过千篇一律的卡通片,而本次将换成CoreAnimation来形成这么些干活儿

关于图层

在iOS中,每一个UIView都独具一个与之绑定的CALayer图层对象,其承受视图内容的绘图与显示。跟前者一样,CALayer也存有树状的子图层结构,以及相似的接口方法。CALayer是图层的基类,紧要提供了视图显示范围、图层结构接口等性能,我们透过利用它的子类。下面是一段在控制器的界面中央添加一个圆形的红色图层:

override func viewDidLoad() {
    super.viewDidLoad()

    let layer = CAShapeLayer()
    layer.fillColor = UIColor.purpleColor().CGColor
    layer.path = UIBezierPath(arcCenter: CGPoint(x: UIScreen.mainScreen().bounds.width / 2, y: UIScreen.mainScreen().bounds.height / 2), radius: 100, startAngle: 0, endAngle: 2.0*CGFloat(M_PI), clockwise: false).CGPath
    self.view.layer.addSublayer(layer)
}

同样的,每一个CALayer留存一个sublayers的数组属性,我们也足以遍历这些数组来完成移除子视图之类的操作:

for sublayer in self.view.layer.sublayers! {
    print("\(sublayer)")
    sublayer.removeFromSuperlayer()
}

出于主题动画框架的动画都是依照CALayer的图层举行添加兑现的,所以图层的增长移除方法是最常用的措施。当然,还有一个addAnimation(anim:forKey:)接口用来给图层添加动画

基本功动画

基础动画CABasicAnimation是最常用来兑现动画效果的卡通类,其继承自CAAnimation动画基类,为图层动画效果落实了一个keyPath性能,大家经过设置这多少个特性来为相应的keyPath属性值执行动画效果。动画类提供了fromValuetoValue七个属性用来设置动画的起先和得了的值,比如下边一段代码让添加到视图上的褐色图层变得透明:

@IBAction func actionToAnimatedLayer(sender: AnyObject) {
    let animation = CABasicAnimation(keyPath: "opacity")
    animation.fromValue = NSNumber(double: 1)
    animation.toValue = NSNumber(double: 0)
    animation.duration = 1
    layer.addAnimation(animation, forKey: nil)
}

地点的代码用动画表现了在1秒内让图层的opacity属性从10的长河。但下面不难看出在动画截至之后,黑色的图层没有保障opacity等于0的情状,而是重返了动画片最起首的情状。这是怎么吧?

在上一篇中笔者提到过在每一个CALayer中设有着模型呈现渲染两种图层树,正是这多少个图层树共同效能来形成隐式动画。那么使用基本动画的时候,实际上CABasicAnimation会基于动画时长统计出每一帧的卡通属性的值,然后实时提交给呈现树来呈现对应时间点的视图效果,在动画停止时CAAnimation对象会自行从图层上移除。而由于在所有动画过程模型树的值没有改动,所以在动画截至的时候呈现树会再一次从模型树赢得图层的习性重新绘制。对此,存在这三种缓解方案:

  • 在促成动画的时候还要修改opacity,保证模型树的数目同步
    @IBAction func actionToAnimatedLayer(sender: AnyObject) {
    let animation = CABasicAnimation(keyPath: “opacity”)
    animation.fromValue = NSNumber(double: 1)
    animation.toValue = NSNumber(double: 0)
    animation.fillMode = kCAFillModeForwards
    animation.removedOnCompletion = false
    animation.duration = 1

        layer.addAnimation(animation, forKey: nil)
    }
    
  • 取消CAAnimation的自发性移除,并且安装在动画截至后保持动画的截至状态
    @IBAction func actionToAnimatedLayer(sender: AnyObject) {
    let animation = CABasicAnimation(keyPath: “opacity”)
    animation.fromValue = NSNumber(double: 1)
    animation.toValue = NSNumber(double: 0)
    animation.fillMode = kCAFillModeForwards
    animation.removedOnCompletion = false
    animation.duration = 1
    layer.addAnimation(animation, forKey: nil)
    }

  • 实现动画代理方法。综合下边二种形式的操作
    @IBAction func actionToAnimatedLayer(sender: AnyObject) {
    let animation = CABasicAnimation(keyPath: “opacity”)
    animation.fromValue = NSNumber(double: 1)
    animation.toValue = NSNumber(double: 0)
    animation.fillMode = kCAFillModeForwards
    animation.removedOnCompletion = false
    animation.duration = 1

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

相比前两种方法,实现代理然后设置属性的做法有些零乱且低效的觉得。但在好几应用场景下,咱们需要在动画停止时移除图层或此外操作,通过兑现代理是最好的做法。其他常用的keyPath动画值可以在这里查看

动画组

继之下边的卡通效果,我想要在潜移默化的根基上加码一个形变动画,那么我急需创建六个CABasicAnimation目的来成功这一工作:

@IBAction func actionToAnimatedLayer(sender: AnyObject) {
    let opacity = CABasicAnimation(keyPath: "opacity")
    opacity.fromValue = NSNumber(double: 1)
    opacity.toValue = NSNumber(double: 0)
    opacity.duration = 1

    layer.addAnimation(opacity, forKey: "opacity")

    let scale = CABasicAnimation(keyPath: "transform")
    scale.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
    scale.toValue = NSValue(CATransform3D: CATransform3DMakeScale(2, 2, 2))
    scale.duration = 1

    layer.addAnimation(scale, forKey: "scale")
}

除却上边这段代码之外,在CoreAnimation框架中提供了一个CAAnimationGroup类来将七个卡通对象整合成一个目的添加到图层上。从利用实现的角度而言,并不会跟下边的代码有其余出入,却足以让代码的逻辑更是清晰:

@IBAction func actionToAnimatedLayer(sender: AnyObject) {
    // create animations

    let group = CAAnimationGroup()
    group.animations = [opacity, scale]
    group.duration = 1
    layer.addAnimation(group, forKey: "group")
}

按钮动画

第一是卡通片中的形变和透明渐变分别对应transform以及opacity两个keyPath,其次,动画图层不是按钮本身的图层,因而还索要添加额外的一个图层。此外,动画存在外扩和内扩的卡通效果,由此我们还需要定义一个枚举来区别:

enum LXDAnimationType {
    case Inner
    case Outer
}

在swift的extension中不帮助添加储值属性,由此咱们需要利用到runtime的动态绑定来完成对按钮包括动画类型、动画颜色五个特性的扩充:

private var kAnimationTypeKey: UInt = 0
private var kAnimationColorKey: UInt = 1
extension UIButton {

    enum LXDAnimationType {
        case Inner
        case Outer
    }

    //MARK: - Expand property
    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.whiteColor()
        }
        set {
            objc_setAssociatedObject(self, &kAnimationColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

接下去是何许保证大家在点击按钮的时候可以举办我们的动画片。这里我们经过重写按钮的sendAction(action:to:forEvent:)方式来施行动画,那一个方法在每一次按钮发送一个事变时会被调用。同理,当用户点击按钮时也会调用这个办法:

//MARK: - Override
public override func sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) {
    super.sendAction(action, to: target, forEvent: event)

    if let type = animationType {
        var rect: CGRect?
        var radius = self.layer.cornerRadius

        var pos = touchPoint(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!, radius: radius, position: pos)
        let group = animateGroup(scale)
        self.layer.addSublayer(layer)
        group.setValue(layer, forKey: "animatedLayer")
        layer.addAnimation(group, forKey: "buttonAnimation")
    }
}

public override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
    if let layer = anim.valueForKey("animatedLayer") as? CALayer {
        layer .removeFromSuperlayer()
    }
}


//MARK: - Private
private func touchPoint(event: UIEvent?) -> CGPoint {
    if let touch = event?.allTouches()?.first {
        return touch.locationInView(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.clearColor().CGColor
        break
    }
    return layer
}

private func animateGroup(scale: CGFloat) -> CAAnimationGroup {
    let opacityAnim = CABasicAnimation(keyPath: "opacity")
    opacityAnim.fromValue = NSNumber(double: 1)
    opacityAnim.toValue = NSNumber(double: 0)

    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
    group.fillMode = kCAFillModeBoth
    group.removedOnCompletion = false
    return group
}

扩张之后的按钮只要设置animationType其一特性之后就会落实在点击时的动画效果

animateButton.animationType = .Outer

尾话

相比较之下起外国的采纳,国内的卡通片效果要显得内敛得多,甚至很多的app是没考虑过动画制作的。然而在活动端支付已然是一片血海的明日,雅观的卡通片效果仍然会为你的使用带来留存,前提是您的应用要靠谱——单纯的动效留不住人。由此,理解动画是着重的一项基本技能。本文demo

上一篇:认识CoreAnimation
下一篇:定时器动画

转载请注脚本文作者和转载地址

相关文章