I'm trying to display an SVG graphic in a UIWebView for iOS. However with the images I am using the web view is adding large amounts of white space, 100s of pixels, above and below the graphic. Leading to the image being half of the screen vertically and you have to scroll to get it fully into view.
I've searched high and low on this issue and tried many, many things. I've got a 'good enough' workaround that I will share here. I'm asking this question in case anyone has a better fix and to help anyone else who encounters the same issue.
The real images I'm using are of sheet music generated by another tool (lilypond post processed by inkscape). However this simple rectangle which is twice as wide as it is tall shows the exact same issue.
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" viewBox="0 0 20 10" width="100%" height="100%">
<rect height="10" style="fill:currentColor" width="20" x="0" y="0" />
</svg>
If you view that in Safari or Chrome then it displays perfectly, filling the window and starting at the top. But in UIWebView it has this massive amount of white space above and below it. If you remove the viewBox attribute then the random extra white space disappears, but this isn't useful as then the graphic is miniscule. And anyway the SVG is correct. Calling [webView sizeThatFits:CGSizeZero]
in webViewDidFinishLoad
returns 1024x1120. Not 1024x512 as I would expect
In my case I get the UIWebView to display the raw SVG. Here are the things I have tried that have no effect.
- Wrapping the SVG in HTML
Wrapping the SVG in HTML and adding the following CSS:
* { margin: 0; padding: 0; } body { overflow: hidden; }
Putting the following code in
webViewDidFinishLoading
, which I got somewhere else on StackOverflow.- (void)webViewDidFinishLoad:(UIWebView *)webView { CGRect frame = webView.frame; frame.size.height = 1; webView.frame = frame; CGSize fittingSize = [webView sizeThatFits:CGSizeZero]; frame.size = fittingSize; webView.frame = frame; }
A partial workaround is to add the attribute preserveAspectRatio="xMinYMin meet"
in the svg tag.
<svg xmlns="http://www.w3.org/2000/svg" version="1.2"
preserveAspectRatio="xMinYMin meet" viewBox="0 0 20 10" width="100%" height="100%">
<rect height="10" style="fill:currentColor" width="20" x="0" y="0" />
</svg>
That removes the excess whitespace at the top of the image, but leaves it at the bottom. It is only a partial workaround as though it initially looks right you can still scroll when you shouldn't be able to. Therefore I still need to disable scrolling to keep it looking right.
Any thoughts?