Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 416
rushafi Avatar asked Mar 13 '23 14:03

rushafi


1 Answers

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")
like image 153
Ranknoodle Avatar answered May 01 '23 21:05

Ranknoodle