So, what I’m trying to do is to read an svg-file from disk with the new Vector Graphics package. Any one know how this might be done? Reading the raw bytes from disk is no problem.
Had it been a .png, I would have used the method LoadBytes. There is no such method in the SVGImage.
Depends whether you’re doing it at Edit time (in the Editor) or at runtime.
Editor use
In the Editor, you can simply drag the SVG into the project and under/within it in the Project window will appear 1 sprite that you can use. Selecting the SVG file in the Project window will show you details in the inspector for tweaking how it’s converted etc. I don’t believe anyone (at this time) knows how to access this at runtime though so for me the more useful is…
Runtime use
For runtime use, you need the text of the SVG. While you can go through normal C# I/O operations, the simplest way to achieve this is just adding a “.bytes” to the end of the SVG’s filename outside Unity (Explorer oin Windows etc). Then you can reference it as a TextAsset which has a .text property which puls the whole text in. Here’s some code I’m using successfully (hopefully all of it copied and pasted as successfully ) Oh btw this can only be done at runtime – trying to do at other times causes an error relating to Sprite.OverrideGeometry() – I’m still trying to figure this out.
public class SVGInScene : MonoBehaviour {
public TextAsset svgAsset;
public SVGTesselationOptions tesselationOptions;
public void Start() {
initSVG();
}
private void initSVG() {
// Dynamically import the SVG data, and tessellate the resulting vector scene.
var sceneInfo = loadSVG();
var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tesselationOptions.getAsTessellationOptions());
// Build a sprite with the tessellated geometry.
var sprite = VectorUtils.BuildSprite(geoms, 10.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
sprite.name = svgAsset.name;
var spriteRenderer = gameObject.AddComponent<SpriteRenderer>(); // or get existing one
spriteRenderer.sprite = sprite;
}
private SVGParser.SceneInfo loadSVG() {
using (var reader = new StringReader(svgAsset.text)) { // not strictly needed but in case switch later.
return SVGParser.ImportSVG(reader);
}
}
}