
SVG problem in iOS
During our development, we were forced to use SVG files. It was not the case for usage, we were just showing it and that was all. The need of it was urgent as we were simulating users closing and coloring it’s close. What could feel better than SVG? We thought — “ nothing”, as SVG was initially built for such things. In the end, I learnt one strict rule — “Never use SVG”. As SVG is not supported natively we were forced to use some external libraries for our purposes. All of them works in one way — driving SVG using context and CGPath. Unfortunately, it’s not the fastest UI operation that can be performed. As it’s working with UI, it should definitely be performed in the main thread, otherwise, it will crash. In the end, we got horrible lags and we were totally disappointed with such result.
Our solution was to simulate SVG by using UIImages layers. Our main Idea came from how SVG file builds.
If simply, then SVG file is some sort of XML with some changes. Changing component in SVG file means finding the proper tag and changing it’s value or attribute, depending on your needs.
We thought — what if we build a system of tags, just by layering UIImages one after the other.
The main idea was to lay simple SVG pieces one on another, and when you need to change something, you are not parsing SVG file, but simply changing the UIImage value that represents needed peace. The logic of changing was the same as before, changed only its implementation. However, still, one image for one tag was not enough. Imagine that our SVG as well depends on color. What then? Then we need one more UIImage that will represent a color piece. Now we got that each simple piece was represented by two images. One for the outline and one for color. If SVG depends on some other things that should be shown and changed, then it causes adding one more UIImage. Now we got that each simple separate piece was represented with several images. Each image was layered in a proper way and was responsible for piecing single role(such as color showing).
When we need to change some piece, we are not parsing SVG file, but searching needed piece. If that was a specific piece role, such as color, then we will be searching related Image component and changing it. And all of these are encapsulated in one place. Outside was given a pretty simple interface, almost similar to that of SVG, so that anytime it can be easily changed back or to other solution.
In the end, when we built this interpreter we get a lot of benefits. It’s really easy to work with, easy to understand, flexible to change. And the most essential thing is — we removed those horrible lags. Still, our work was based on simple SVG representations. I’m pretty sure that with really complex SVG files there may be some performance problems.
