Swift SVG Fil Color to SVGImage

Solutions Collect From Internet About “Swift SVG Fil Color to SVGImage”

Wish Swift adds this feature in their next release

After a nightmare, I came up with this solution for
Using SVG in Swift which fits automatically for the View and can add fill colors to it in just one line of code

This is for all who don’t wish to struggle like me

|*| Usage :

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

// Can use this Image anywhere in your code

|*| Steps :

I used the simple SwiftSVG library for getting UIView from SVG File

|*| Install SwiftSVG Library

1) Use pod to install :

// For Swift 3

pod 'SwiftSVG'

// For Swift 2.3

pod 'SwiftSVG', '1.1.5'

2) Add framework

Goto AppSettings
-> General Tab
-> Scroll down to Linked Frameworks and Libraries
-> Click on plus icon
-> Select SVG.framework

3) Add below code anywhere in your project

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!
    }
}