Swift SVG 填充颜色到 SVGImage

Suj*_*U N 1 svg image ios svgkit swift

我正在使用 SVGKit 来显示图像

https://github.com/SVGKit/SVGKit/

如何为 SVGImage 应用填充颜色

let namSvgImgVar = SVGKImage(named: namSvgImg)
namSvgImgVar.setFillColor()
Run Code Online (Sandbox Code Playgroud)

想要实现这个setFillColor函数

Suj*_*U N 6

希望 Swift 在下一个版本中添加此功能

经过一场噩梦后,我想出了这个
在 Swift 中使用 SVG 的解决方案,它自动适合视图,并且只需一行代码即可为其添加填充颜色

这是给所有像我一样不想奋斗的人的

|*| 用法 :

let svgImgVar = getSvgImgFnc("svgImjFileName", ClrVar : ClrVar)

// Can use this Image anywhere in your code
Run Code Online (Sandbox Code Playgroud)

|*| 脚步 :

我使用简单的SwiftSVG库从 SVG 文件获取 UIView

|*| 安装SwiftSVG

1)使用pod安装:

// 对于 Swift 3

pod 'SwiftSVG'
Run Code Online (Sandbox Code Playgroud)

// 对于 Swift 2.3

pod 'SwiftSVG', '1.1.5'
Run Code Online (Sandbox Code Playgroud)

2)添加框架

转到 AppSettings
-> 常规选项卡
-> 向下滚动到链接的框架和库
-> 单击加号图标
-> 选择 SVG.framework

3)在项目中的任意位置添加以下代码

func getSvgImgFnc(svgImjFileNameVar: String, ClrVar: UIColor) -> UIImage
{
    let svgURL = NSBundle.mainBundle().URLForResource(svgImjFileNameVar, withExtension: "svg")
    let svgVyuVar = UIView(SVGURL: svgURL!)

    /* The width, height and viewPort are set to 100 

        <svg xmlns="http://www.w3.org/2000/svg"
            width="100%" height="100%"
            viewBox="0 0 100 100">

        So we need to set UIView Rect also same
    */

    svgVyuVar.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    for svgVyuLyrIdx in svgVyuVar.layer.sublayers!
    {
        for subSvgVyuLyrIdx in svgVyuLyrIdx.sublayers!
        {
            if(subSvgVyuLyrIdx.isKindOfClass(CAShapeLayer))
            {
                let SvgShpLyrIdx = subSvgVyuLyrIdx as? CAShapeLayer
                SvgShpLyrIdx!.fillColor = ClrVar.CGColor
            }
        }
    }
    return svgVyuVar.getImgFromVyuFnc()
}

extension UIView
{
    func getImgFromVyuFnc() -> UIImage
    {
        UIGraphicsBeginImageContext(self.frame.size)

        self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return image!
    }
}
Run Code Online (Sandbox Code Playgroud)