layer Animation(五)

Wednesday, March 21, 2018

Stroke and path animations

  • 今天来讲解一个下拉刷新的动画,效果如下

[WPGP gif_id="140” width="400”]

  • 如上图所示,在下拉的过程中,会不断完成一个圆形,并且到最后会进入一个刷新动画。

  • 所有复杂的动画,都是可以拆解成一个个简单的动画,最后组合而成,对于这个下拉刷新动画也是如此。具体的下拉刷新机制,不在这里阐述,我们先看看下拉过程中,不断完成一个圆形的动画是怎么完成的。

    //先制作一个完整的虚线圆形 let ovalShapeLayer: CAShapeLayer = CAShapeLayer() ovalShapeLayer.strokeColor = UIColor.white.cgColor ovalShapeLayer.fillColor = UIColor.clear.cgColor ovalShapeLayer.lineWidth = 4.0 ovalShapeLaeyr.lineDashPattern = [2, 3]

    let refreshRadius = frame.size.height / 2 * 0.8

    ovalShapeLayer.path = UIBezierPath(ovalIn: CGRect.init(x: frame.size.width / 2.0 - refreshRadius, y: frame.size.height / 2.0 - refreshRadius, width: refreshRadius, height: refreshRadius)).cgPath layer.addSublayer(ovalShapeLayer)

  • 上述代码,就已经创建好一个完整的虚线圆了,现在我们要考虑怎么让他跟随滑动而逐渐完成一个圆。具体 scollview 怎么去计算,这里不在阐述,我们需要修改到的参数就是 strokeEnd。计算出滑动的百分比,再写入这个属性,即可实现该动画效果。

    //只需执行这行代码即可实现 ovalShapeLayer.strokeEnd = progress

  • 下面我们先把飞机放上去

    let airplaneImage = UIImage(named: “airplane.png”)! airplaneLayer.contents = airplaneImage.cgImage airplaneLayer.bounds = CGRect(x: 0.0, y: 0.0, width: airplaneImage.size.width, height: airplaneImage.size.height) airplaneLayer.position = CGPoint(x: frame.size.width/2 + frame.size.height/2 * 0.8, y: frame.size.height/2) layer.addSublayer(airplaneLayer)

  • 下面我们要实现一个,圆的虚线不断转动问题,并且看起来像是一直在追赶的动画效果

    //这里有个小技巧,将 strokeStart的数值从-0.5开始,这样就能实现追赶效果了。 let strokeStartAnimaiton = CABasicAnimation(keyPath: “strokeStart”) strokeStartAnimation.fromValue = -0.5 strokeStartAnimaiotn.toValue = 1

    let strokeEndAniamtion = CABasicAnimation(keyPath: “strokeEnd”) strokeEndAnimation.fromeValue = 0 strokeEndAnimation.toValue = 1

    let strokeAnimaitonGroup = CAAnimationGroup() strokeAnimaitonGroup.duration = 1.5 strokeAnimationGroup.repeatDuration = 5.0 strokeAnimationGroup.animations = [strokeStartAnimaiton, strokeEndAniamtion] ovalShapeLayer.add(strokeAnimationGroup, forKey: nil)

  • 最后我们要让飞机动起来,这里又分两部,一个是让飞机实现位移动画,另一个是让飞机能旋转起来。

    //可以用 path 来实现动画, transform.rotation 实现旋转 let flightAnimation = CAKeyframeAnimation(keyPath: “position”) flightAnimation.path = ovalShapeLayer.path flightAnimaiton.calculationMode = KCAAnimationPaced

    let airplaneOrientationAnimation = CABasicAnimation(keyPaht: “transform.rotation”) airplaneOrientationAnimation.fromValue = 0 airplaneOrientationAnimation.toValue = 2.0 * .pi

    let flightAnimationGroup = CAAnimationGroup() flightAnimationGroup.duration = 1.5 flightAnimationGroup.repeatDuration = 5.0 flightAnimationGroup.animaitons = [flightAnimation, airplaneOrientationAnimation]

    airplaneLayer.add(flightAnimationGroup, forKey: nil)

iOS动画

Moya 的实现(一)

Layer Animation(四)