Search code examples
xcodesvguikit

How to Display and Fill SVG Countries Based on Percentage in iOS (UIKit)


I'm working on an iOS project where I need to display an SVG map of a continent or country, and dynamically fill each region based on a given percentage, similar to a choropleth map. Here's an example of what I'm aiming for with a map of the UK:

SVG image of UK

I've experimented with SVGKit and SwiftSVG to load and display the SVG, but I'm struggling to fill the regions with a color that reflects the percentage (like the red color on the image).

Does anyone know how i could achieve it, or know a better approach/alternative solution for achieving the same result without using SVG? I'm open to any library recommendations or different techniques suitable for iOS development.


Solution

  • Most of the SVG libraries create a CAShapeLayer for each element in the SVG file.

    So, if we use a simple "UK Regions" SVG map that looks like this:

    enter image description here

    and change the fill color of each region to make it easier to see what's going on:

    enter image description here

    a library such as SVGKit will generate layers like this:

    enter image description here

    So, if we want to "fill a region by percentage" we need to manipulate the layer(s).

    One approach would be to duplicate the target layer and then mask it by the desired percentage:

    enter image description here

    Here we're "filling" by 50% ...

    enter image description here