mchoe / SwiftSVG

A simple, performant, and lightweight SVG parser
Other
1.92k stars 230 forks source link

Support for currentColor #142

Closed onato closed 4 years ago

onato commented 5 years ago

SVG supports setting the fill color to currentColor. This can be seen in the following example where the group sets it's children's default fill color.

<svg id="meta-path" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15">
  <g fill="currentColor">
    <rect fill="none" width="15" height="15"/>
    <circle fill="#CCCCCC" cx="8" cy="8" r="6"/>
    <circle cx="7.5" cy="7.5" r="6"/>
  </g>
</svg>

Setting the currentColor to orange should looks like this:

Screen Shot 2019-07-30 at 5 46 59 PM

I can't simply set the fill color because this will overwrite the color of the rect and just render a square.

It doesn't seem trivial to add support for passing the current color into the initializers. I have a dirty solution that sets the fillColor of any layer that is black (The currentColor ends up being black).

extension SVGLayer {
    func updateDefaultFill(color: UIColor) {
        self.applyOnSublayers(ofType: CAShapeLayer.self) { (thisShapeLayer) in
            let colorComponents = thisShapeLayer.fillColor?.components ?? []
            let isUndefined = colorComponents.count == 4
                && colorComponents[0] == 0
                && colorComponents[1] == 0
                && colorComponents[2] == 0
                && colorComponents[3] == 1
            if isUndefined {
                thisShapeLayer.fillColor = color.cgColor
            }
        }
    }
}
mchoe commented 4 years ago

I don't think I'll be able to add support for this in any time in the near future. I have yet another rewrite of the library in mind that could support this feature, so I want to keep it in mind. Thanks @onato for the suggestion though.

In the meantime, you may be able to grab the layer by the name property on the CALayer which maps from the id attribute on the <path> or <g>. Check out the Identifiable protocol for more info.