如何在iOS中使用SVGKit将SVG路径组件解析为UIBezierPath? [英] How to parse SVG path component to UIBezierPath using SVGKit in iOS?

查看:118
本文介绍了如何在iOS中使用SVGKit将SVG路径组件解析为UIBezierPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift在iOS中为SVG图像制作动画.我已经能够使用SVGKit( https://github.com/SVGKit/SVGKit ),但要对其进行动画处理,我需要将SVG path元素转换为UIBezierPath.我可以使用其他库来做到这一点,但是如果我可以单独使用SVGKit来完成所有工作,那将是很好的.我也找不到任何直接的方法来获取path元素.

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.

推荐答案

我在使用Swift和使用SVGKit时遇到了同样的问题.即使遵循此简单教程并将其转换为swift,我可以渲染SVG,但不能为线条绘制动画.对我有用的是切换到 PocketSVG

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

它们具有在每个图层上进行迭代的功能,这就是我使用它为SVG文件制作动画的方式:

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

这篇关于如何在iOS中使用SVGKit将SVG路径组件解析为UIBezierPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆