swhitty / SwiftDraw

Swift library and command line tool to convert SVGs into SFSymbol, PNG, PDF and Swift source code.
zlib License
389 stars 49 forks source link

Support for different canvas units (SVGLength) #42

Open xhruso00 opened 4 months ago

xhruso00 commented 4 months ago

SVG files that use different units are currently rasterized as pixels. 10cm becomes 10px

<svg height="10cm" width="10cm" xmlns="http://www.w3.org/2000/svg">
    <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

https://developer.mozilla.org/en-US/docs/Web/API/SVGLength

https://github.com/WebKit/WebKit/blob/3b35a19d0a910ba3376525d9dae67fe6b4d5016f/Source/WebCore/svg/SVGLength.h

Screenshot 2024-05-25 at 19 06 45
xhruso00 commented 4 months ago

Another common length unit is 100%

This is a wider issue mainly coming from inline SVGs used on the web. Is common that canvas size is missing completely or just height is being defined.

I think the specification doesn't mention SVGs without width/height/viewBox as invalid. They just inherit the viewPort size.

https://www.w3.org/TR/SVG11/coords.html

PS: The SVG I have attached gives different size results WKWebView vs WebView (if size+viewBox is unspecified). Old webview one could easily determine size of DOM element. WKWebView one has to use getBBox() which doesn't support stroke so the resulting size is different. On top native NSImage supports loading SVG since sonoma but also gives slightly wrong size for these "ambiguous" SVGs

https://medium.com/@AaronGustafson/please-size-your-inline-svgs-4f915f59e48c

I might have misunderstood the library's description. It might be sufficient to mention this issue in the readme that is not supposed for general use.

swhitty commented 3 months ago

Thank you for pointing this out 🙏🏼

I have added support for using absolute units for any position, size or coordinate within https://github.com/swhitty/SwiftDraw/pull/45

Relative units like % are trickier so are not supported, but please try it out on main branch — I'm interested in how it works for you.