本文介绍了画线动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在屏幕中央画一条线,像蛇一样对其进行动画处理

I want to have a line in the center of the screen and animate it like a snake

这是我要制作的分步动画

This is step by step animation I want to make

我该怎么做?

推荐答案

您可以在上为路径的笔触末端设置动画。 CAShapeLayer ,例如

You can animate the end of the stroke of a path on a CAShapeLayer, e.g.,

weak var shapeLayer: CAShapeLayer?

@IBAction func didTapButton(_ sender: Any) {
    // remove old shape layer if any

    self.shapeLayer?.removeFromSuperlayer()

    // create whatever path you want

    let path = UIBezierPath()
    path.move(to: CGPoint(x: 10, y: 50))
    path.addLine(to: CGPoint(x: 200, y: 50))
    path.addLine(to: CGPoint(x: 200, y: 240))

    // create shape layer for that path

    let shapeLayer = CAShapeLayer()
    shapeLayer.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
    shapeLayer.strokeColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor
    shapeLayer.lineWidth = 4
    shapeLayer.path = path.cgPath

    // animate it

    view.layer.addSublayer(shapeLayer)
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 0
    animation.duration = 2
    shapeLayer.add(animation, forKey: "MyAnimation")

    // save shape layer

    self.shapeLayer = shapeLayer
}

得出:

很显然,您可以将 UIBezierPath 更改为适合您的兴趣的内容。例如,路径中可以有空格。或者甚至不需要直线路径。

Clearly, you can change the UIBezierPath to whatever suits your interests. For example, you could have spaces in the path. Or you don't even need to have rectilinear paths:

let path = UIBezierPath()
path.move(to: CGPoint(x: 10, y: 130))
path.addCurve(to: CGPoint(x: 210, y: 200), controlPoint1: CGPoint(x: 50, y: -100), controlPoint2: CGPoint(x: 100, y: 350))

您还可以组合开始和结束动画在 CAAnimationGroup 的笔画末尾:

You can also combine animation of both the start and end of the stroke in a CAAnimationGroup:

// create shape layer for that path (this defines what the path looks like when the animation is done)

let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
shapeLayer.strokeColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1).cgColor
shapeLayer.lineWidth = 5
shapeLayer.path = path.cgPath
shapeLayer.strokeStart = 0.8

let startAnimation = CABasicAnimation(keyPath: "strokeStart")
startAnimation.fromValue = 0
startAnimation.toValue = 0.8

let endAnimation = CABasicAnimation(keyPath: "strokeEnd")
endAnimation.fromValue = 0.2
endAnimation.toValue = 1.0

let animation = CAAnimationGroup()
animation.animations = [startAnimation, endAnimation]
animation.duration = 2
shapeLayer.add(animation, forKey: "MyAnimation")

收益:

CoreAnimation使您可以很好地控制描边路径的呈现方式。

CoreAnimation gives you a lot of control over how the stroked path is rendered.

这篇关于画线动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:09