如何在IOS中设置SVG路径的动画?

时间:2011-05-07 21:55:22

标签: ios animation svg

我有一个像这样的SVG路径:

<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" version="1.1"  baseProfile="full"> 
    <path d="M47.16,66.38c0.62,1.65-0.03,2.93-0.92,4.28c-5.17,7.8-8.02,11.38-14.99,18.84c-2.11,2.25-1.5,4.18,2,3.75c7.35-0.91,28.19-5.83,40.16-7.95" style="fill:none;stroke:black;stroke-width:2" />
</svg>

我可以渲染路径,但似乎无法找到使路径变为动画的方法,以便它看起来像是“正在绘制”,就好像用铅笔一样。 animate节点适用于单个坐标,但不适用于路径。

我最终将使用解析器或UIWebView在iPhone应用程序中使用此动画。

3 个答案:

答案 0 :(得分:8)

尝试设置'stroke-dashoffset'的动画(请注意,您需要匹配'stroke-dasharray'),请参阅this example。需要计算才能成功使用此路径的路径长度可以通过以下脚本获取:

var pathlength = yourPathElm.getTotalLength()

查看example上的来源,看看它是如何完成的。

答案 1 :(得分:2)

我尝试了很长时间没有在标题中添加额外的脚本(我不知道javascript没有帮助),所以这是解决方案:

<path d="..." stroke-dasharray="">
  <animate attributeName="stroke-dashoffset" from="" to="0" dur="1s" begin="0s"
           onload="var length = parentNode.getTotalLength();
                   parentNode.setAttribute('stroke-dasharray',length+','+length);
                   this.setAttribute('from',length)" />
</path>

我在这里添加了额外的换行符以便于阅读。

这在 SVG (虽然不是HTML)中是合法的,因为the svg:animate element allows onload是大多数HTML元素所不具备的。

答案 2 :(得分:0)

一旦你渲染了你的SVG路径,让它看起来像是用铅笔绘制的,你可以简单地用一个不透明的层覆盖它,然后沿着路径动画这个层的移动。

要查找您将移动图层的CGPath,您可以使用此库: https://github.com/arielelkin/PocketSVG

这会将SVG数据解析为UIBezierPath。然后:

SvgToBezier *myBezier = [[SvgToBezier alloc] initFromSVGPathNodeDAttr:@"M176.17,369.617c0,0,335.106-189.361,214.894,38.298s129.787,282.978,178.723,42.553C618.724,210.042,834.681,87.702,790,307.915" rect:CGRectMake(0,0,1024,768)];

UIBezierPath *myPath = myBezier.bezier;

CAKeyframeAnimation *mySVGPathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
bounceAnimLeft.duration = 3;
bounceAnimLeft.path = myPath.CGPath;

[myObjectToMove.layer addAnimation:mySVGPathAnimation forKey:@"pathAnimation"];
相关问题