gpt4 book ai didi

swift - 画线动画

转载 作者:IT王子 更新时间:2023-10-29 05:17:58 30 4
gpt4 key购买 nike

我想在屏幕中央有一条线,让它像一条蛇一样动起来

这是我要制作的一步步动画

enter image description here

我该怎么做?

最佳答案

您可以在 CAShapeLayer 上为 path 的笔划末端设置动画,例如,

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
}

产生:

stroked path

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

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 中组合笔划开始和结束的动画:

// 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")

产量:

enter image description here

CoreAnimation 使您可以对描边路径的渲染方式进行大量控制。

关于swift - 画线动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978418/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com