首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在iOS中使用SVGKit将SVG path组件解析为UIBezierPath?

如何在iOS中使用SVGKit将SVG path组件解析为UIBezierPath?
EN

Stack Overflow用户
提问于 2016-04-17 14:24:33
回答 2查看 4.2K关注 0票数 4

我正在使用Swift在iOS中制作SVG图像的动画。我已经能够使用SVGKit (https://github.com/SVGKit/SVGKit)轻松地呈现SVG,但是为了使其具有动画效果,我需要将SVG path元素转换为UIBezierPath。我可以使用其他库来做到这一点,但如果我可以只使用SVGKit来完成所有这些工作,那就更好了。我还没有找到任何直接的方法来获取path元素。

EN

回答 2

Stack Overflow用户

发布于 2016-11-19 01:43:39

我在使用Swift和使用SVGKit时也遇到了同样的问题。即使在遵循这个simple tutorial并将其转换为swift之后,我仍然可以渲染SVG,但不能对线条绘图进行动画处理。对我来说起作用的是切换到PocketSVG

它们有一个遍历每一层的函数,这就是我如何使用它来制作SVG文件的动画:

代码语言:javascript
复制
  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")
票数 4
EN

Stack Overflow用户

发布于 2016-10-14 22:28:13

路径可以通过在苹果的类上调用.path来获得。我建议你阅读苹果的CoreAnimation文档,尤其是CAShapeLayer (SVGKit大量使用它)。

苹果还提供了转换为UIBezierPath的代码-同样,请搜索苹果文档以了解如何执行此操作的详细信息。例如:

*)bezierPathWithCGPath:(CGPathRef)CGPath;

  • (UIBezierPath
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36673346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档