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

Rémi B.
  • 2,410
  • 11
  • 17
Sujay U N
  • 4,974
  • 11
  • 52
  • 88

3 Answers3

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!
    }
}
Sujay U N
  • 4,974
  • 11
  • 52
  • 88
  • 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. – Narasimha Nallamsetty Dec 02 '19 at 12:50
  • 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. – Narasimha Nallamsetty Dec 02 '19 at 12:57
  • Sujay, this code is not working in swift 5. Please convert your code snippet to swift-5 – Pavan Kumar Idapalapati Dec 28 '19 at 05:01
  • @NarasimhaNallamsetty did you find a solution for this error – Ayman Dec 14 '20 at 15:09
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
        }
    }

}
K Ravi Kumar
  • 71
  • 1
  • 2
  • 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. – dkb Jul 12 '19 at 10:56
-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))
        }
    }
}
Rémi B.
  • 2,410
  • 11
  • 17
  • 1
    The question is asking how to set a fill color for the SVG. Can you clarify how your answer solves that question? – HangarRash Jul 05 '23 at 20:56
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34646699) – Rémi B. Jul 11 '23 at 15:12