我正在使用Swift在iOS中制作SVG图像的动画。我已经能够使用SVGKit (https://github.com/SVGKit/SVGKit)轻松地呈现SVG,但是为了使其具有动画效果,我需要将SVG path元素转换为UIBezierPath。我可以使用其他库来做到这一点,但如果我可以只使用SVGKit来完成所有这些工作,那就更好了。我还没有找到任何直接的方法来获取path元素。
发布于 2016-11-19 01:43:39
我在使用Swift和使用SVGKit时也遇到了同样的问题。即使在遵循这个simple tutorial并将其转换为swift之后,我仍然可以渲染SVG,但不能对线条绘图进行动画处理。对我来说起作用的是切换到PocketSVG
它们有一个遍历每一层的函数,这就是我如何使用它来制作SVG文件的动画:
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")发布于 2016-10-14 22:28:13
路径可以通过在苹果的类上调用.path来获得。我建议你阅读苹果的CoreAnimation文档,尤其是CAShapeLayer (SVGKit大量使用它)。
苹果还提供了转换为UIBezierPath的代码-同样,请搜索苹果文档以了解如何执行此操作的详细信息。例如:
*)bezierPathWithCGPath:(CGPathRef)CGPath;
https://stackoverflow.com/questions/36673346
复制相似问题