前言

在上一篇认识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
下一篇:定时器动画

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

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图