1

I am using SVGKit to display Images

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

How do I apply fill color for the SVGImage

let namSvgImgVar = SVGKImage(named: namSvgImg)
namSvgImgVar.setFillColor()

want to implement this setFillColor function

4 Answers 4

6

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!
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @Sujay, I'm getting below errors in the console. Please let me know the solution. linearGradient is unsupported. For a complete list of supported elements, see the allSupportElements variable in the SVGParserSupportedElements struct. Click through on the elementName variable name to see the SVG tag name.
This is another error in the console. stop is unsupported. For a complete list of supported elements, see the allSupportElements variable in the SVGParserSupportedElements struct. Click through on the elementName variable name to see the SVG tag name.
Sujay, this code is not working in swift 5. Please convert your code snippet to swift-5
@NarasimhaNallamsetty did you find a solution for this error
1

if you have any id for the SVG image, you can fill the colours with respect to the ID.

    let image = SVGKImage(named: "iconName")
    let svgIMGV = SVGKFastImageView(frame: self.imgView.frame)
         svgIMGV.image = image
          svgIMGV.fillTintColor(colorImage: UIColor.red, iconID: "Bank")
// Add in extension SVGKImageView
extension SVGKImageView {
 func fillTintColor(colorImage: UIColor, iconID: String) {
        if self.image != nil && self.image.caLayerTree != nil {
            print(self.image.caLayerTree.sublayers)
            guard let sublayers = self.image.caLayerTree.sublayers else { return }
            fillRecursively(sublayers: sublayers, color: colorImage, iconID: iconID)
        }
    }

     private func fillRecursively(sublayers: [CALayer], color: UIColor, iconID: String, hasFoundLayer: Bool) {
        var isLayerFound = false
        for layer in sublayers {
            if let l = layer as? CAShapeLayer {

                print(l.name)                
                //IF you want to color the specific shapelayer by id else remove the l.name  == "myID"  validation
                if let name =  l.name,  hasFoundLayer == true && name == "myID" {
                    self.colorThatImageWIthColor(color: color, layer: l)
                    print("Colouring FInished")
                }
            } else {
                if layer.name == iconID {
                    if let innerSublayer = layer.sublayers as? [CAShapeLayer] {
                        fillRecursively(sublayers: innerSublayer, color: color, iconID: iconID, hasFoundLayer: true )
                        print("FOund")
                    }
                } else {
                    if let l = layer as? CALayer, let sub = l.sublayers {
                        fillRecursively(sublayers: sub, color: color, iconID: iconID, hasFoundLayer: false)
                    }
                }
            }

        }
    }

    func colorThatImageWIthColor(color: UIColor, layer: CAShapeLayer) {
        if layer.strokeColor != nil {
            layer.strokeColor = color.cgColor
        }
        if layer.fillColor != nil {
            layer.fillColor = color.cgColor
        }
    }

}

1 Comment

Welcome to SO, it is good to add code in support to your answer, also add some explanation with it, which will help SO member and answer will be well received.
0

In iOS 13 withTintColor method allows you to apply a color to your image. Let's look at the below snippet code:

UIImage(named: "MY_IMAGE")?.withTintColor(UIColor.red)

Comments

-1

Another way is to extend WKWebView:

extension WKWebView {
    func displayImage(imageUrl: String) {    
        let path: String = imageUrl        
        if let url = URL(string: path) {
            self.load(URLRequest(url: url))
        }
    }
}

2 Comments

The question is asking how to set a fill color for the SVG. Can you clarify how your answer solves that question?
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.