swift - 用动画绘制路径
问题描述
我想在我的应用程序中绘制一条带动画的路径我使用了下面的代码,但没有动画,它只会将路径的结果添加到 View,即使我使持续时间比正常时间长。
let animation = CABasicAnimation(keyPath: "strokeEnd")
let layer = CAShapeLayer()
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 38.5, y: 88.5))
bezierPath.addCurve(to: CGPoint(x: 86.5, y: 88.5), controlPoint1: CGPoint(x: 41.5, y: 88.5), controlPoint2: CGPoint(x: 86.5, y: 88.5))
bezierPath.addLine(to: CGPoint(x: 86.5, y: 64.5))
bezierPath.addLine(to: CGPoint(x: 145.5, y: 64.5))
UIColor.black.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
layer.path = bezierPath.cgPath
layer.strokeEnd = 0
layer.lineWidth = 1
layer.strokeColor = UIColor.gray.cgColor
layer.fillColor = UIColor.black.cgColor
animation.toValue = 1
animation.duration = 20 // seconds
layer.add(animation, forKey: "Line")
self.view.layer.addSublayer(layer)
我不知道如何让它动画
解决方案
这适用于我的机器,这是完整的课程和代码:
https://github.com/Shah3r/testAnim
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Use CATransaction
CATransaction.begin()
//Set Layer
let layer = CAShapeLayer()
layer.lineWidth = 3
layer.strokeColor = UIColor.red.cgColor
layer.fillColor = UIColor.black.cgColor
//Set Bezier Path
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 38.5, y: 88.5))
bezierPath.addCurve(to: CGPoint(x: 86.5, y: 88.5), controlPoint1: CGPoint(x: 41.5, y: 88.5), controlPoint2: CGPoint(x: 86.5, y: 88.5))
bezierPath.addLine(to: CGPoint(x: 86.5, y: 64.5))
bezierPath.addLine(to: CGPoint(x: 145.5, y: 64.5))
//Set Animation
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0.0
animation.toValue = 1
animation.duration = 7.0 // seconds
//Completion Block
CATransaction.setCompletionBlock{
print("Animation completed")
}
//Add path and animation
layer.path = bezierPath.cgPath
layer.add(animation, forKey: "Line")
CATransaction.commit()
self.view.layer.addSublayer(layer)
}
}
推荐阅读
- excel - 在excel中汇总文本字符串和数字
- kotlin - 如何检查用户是否已将照片上传到我在 Kotlin android 中的图像视图
- java - 在 android studio 的 2 个活动中携带意图数据
- swift - 如何使用 SwiftUI 将值数组写入 Firestore
- excel - 遍历行不遵守排序顺序
- laravel - 无法访问该站点,本地服务器在 Visual Studio 代码上说
- java - 使用 Cumulocity 微服务 JavaSDK 获取应用程序托管对象
- reactjs - 从 localForage getItem 返回一个布尔值
- python - 无法配置 Starlette .env 文件
- json - 如何在 Angular 中创建动态表单控件并从中获取数据