我正在 iOS 中使用 Swift 制作 SVG 图像动画。我已经能够使用 SVGKit 轻松渲染 SVG(https://github.com/SVGKit/SVGKit https://github.com/SVGKit/SVGKit)但要对其进行动画处理,我需要将 SVG 路径元素转换为 UIBezierPath。我可以使用其他库来完成此操作,但如果我可以单独使用 SVGKit 来完成所有这些工作,那就太好了。我还没有找到任何直接的方法来获取路径元素。
我在使用 Swift 和使用 SVGKit 时也遇到了同样的问题。即使遵循这个简单教程 https://medium.com/@kamil.powalowski/paths-animation-of-svg-file-using-svgkit-3d25e7774c89#.4o5b6jtw6并将其转换为 swift,我可以渲染 SVG,但不能对线条图进行动画处理。对我有用的是切换到袖珍SVG https://github.com/pocketsvg/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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)