Render SVGs (C#)

How do I make VisualElements render SVGs in C#? Is it even possible with UI Toolkit in 2021.2.0a16?

You’ll have to install the “com.unity.vectorgraphics” package. Import your SVGs and set the asset type to “UI Toolkit Vector Image”.

When done you can reference the SVG assets as background images on VisualElements or Images.

Ahh, it was the AssetType I had missed. Thanks for the information.

Hm. I did all of the above, but nothing shows up. VisualElement.backgroundImage = new StyleBackground(myVectorImage);
Could it be related to the fact that there is no preview showing up in the project view?

Could be, I can see the SVG preview in the project browser as well as in the inspector. This could point to an import failure.

Can you try with a simpler SVG asset to test with?

Ok I was mistaken, previews aren’t currently showing for Vector Image assets, but they should load fine with UI Toolkit in any case.

Could be a bug with UI Toolkit or could be because windows currently forces all SVGs to become “Microsoft Edge HTML Document”. Everything else seems ok though, so will have to investigate further. Will try with a simpler SVG Asset. The current one has 1331 vertices and 3999 indices.

Edit: Tested with a simple red square (24 vertices and 72 indices), but still nothing. Keep in mind that I am using the built-in UI Toolkit for Unity 2021.2.0a16.

Edit 2: Got it working! Turns out I had used:VisualElement.style.backgroundImage = new StyleBackground(myImage);
instead of:

VisualElement.style.backgroundImage = new StyleBackground(mySVG);

Such a simple mistake, but good thing there was no bug.

Now it works, but the edges are not anti-aliased. In the image below you can see the border of the VisualElement compared to the border of the SVG. This is most likely because the SVG is a mesh. Hopefully it will look crisper sometime in the future.

If this is for an EditorWindow, you can call something like this.SetAntiAliasing(4) in your OnEnable/CreateGUI method.

For runtime, the only option would be to render in an MSAA-enabled RenderTexture, unfortunately. But yes, we have plans for antialiased vector images without MSAA in the future.

Just wondering is there a timeline for this? Will it be done before at least 2022.2? Thanks!

Antialiasing for stock UI Toolkit elements is in the latest 2021.2 beta.

Antialiasing for SVG content is scheduled for later, I think it’s planned for somewhere in 2022, but could take longer.