How to parse SVG path component to UIBezierPath using SVGKit in iOS?

六月ゝ 毕业季﹏ 提交于 2021-02-07 08:19:52

问题


I am animating a SVG image in iOS using Swift. I have been able to render the SVG easily using SVGKit (https://github.com/SVGKit/SVGKit) but to animate it I need to convert the SVG path element to UIBezierPath. I can do so using other libraries but it'd be nice if I could do all of it using SVGKit alone. I haven't find any straight forward way to get the path element as well.


回答1:


I had the same issues with Swift and using SVGKit. Even after following this simple tutorial and converting it to swift, I could render the SVG but not animate the line drawing. What worked for me was switching to PocketSVG

They have a function to iterate over each Layer and this is how I used it to animate a SVG file:

  let url = NSBundle.mainBundle().URLForResource("tiger", withExtension: "svg")!
  let paths = SVGBezierPath.pathsFromSVGAtURL(url)

  for path in paths {
    // Create a layer for each path
    let layer = CAShapeLayer()
    layer.path = path.CGPath

    // Default Settings
    var strokeWidth = CGFloat(4.0)
    var strokeColor = UIColor.blackColor().CGColor
    var fillColor = UIColor.whiteColor().CGColor

    // Inspect the SVG Path Attributes
    print("path.svgAttributes = \(path.svgAttributes)")

    if let strokeValue = path.svgAttributes["stroke-width"] {
      if let strokeN = NSNumberFormatter().numberFromString(strokeValue as! String) {
        strokeWidth = CGFloat(strokeN)
      }
    }

    if let strokeValue = path.svgAttributes["stroke"] {
      strokeColor = strokeValue as! CGColor
    }

    if let fillColorVal = path.svgAttributes["fill"] {
      fillColor = fillColorVal as! CGColor
    }

    // Set its display properties
    layer.lineWidth = strokeWidth
    layer.strokeColor = strokeColor
    layer.fillColor = fillColor

    // Add it to the layer hierarchy
    self.view.layer.addSublayer(layer)

    // Simple Animation
    let animation = CABasicAnimation(keyPath:"strokeEnd")
    animation.duration = 4.0
    animation.fromValue = 0.0
    animation.toValue = 1.0
    animation.fillMode = kCAFillModeForwards
    animation.removedOnCompletion = false
    layer.addAnimation(animation, forKey: "strokeEndAnimation")



回答2:


The path is available by calling .path on Apple's classes. I suggest you read the Apple CoreAnimation documentation, especially CAShapeLayer (which is used heavily by SVGKit).

Apple also provides code for converting to UIBezierPath - again, search the Apple docs for details on how to do this. e.g.:

  • (UIBezierPath *)bezierPathWithCGPath:(CGPathRef)CGPath;


来源:https://stackoverflow.com/questions/36673346/how-to-parse-svg-path-component-to-uibezierpath-using-svgkit-in-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!