首页 > 解决方案 > 用动画绘制路径

问题描述

我想在我的应用程序中绘制一条带动画的路径我使用了下面的代码,但没有动画,它只会将路径的结果添加到 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)

我不知道如何让它动画

标签: swiftcore-animation

解决方案


这适用于我的机器,这是完整的课程和代码:

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)
 }
}

推荐阅读