Search Unity

how to load SVG from url?

Discussion in 'UGUI & TextMesh Pro' started by A_never_kill, Jan 4, 2019.

  1. A_never_kill

    A_never_kill

    Joined:
    Jan 7, 2014
    Posts:
    81
    Hi,
    I am trying to load svg image from Url to UI in my game.But unfortunately of some reason I am unable to do that.kindly let me know if anybody did this thing in past?

    Many thanks
     
  2. rajshirolkar

    rajshirolkar

    Joined:
    May 17, 2020
    Posts:
    2
    Okay so this worked for me. Unity doesn't have a direct way to download a svg image but it can convert the xml string of the svg into an image. So all you have to do is get the raw byte[] data from the download handler and convert it into a UTF-8 string which can then be converted to a SVG image.
    Code :

    Code (CSharp):
    1. IEnumerator downloadSVG()
    2.     {
    3.         string url = <svg-image-url-here>;
    4.         public SVGImage svgimg;
    5.         UnityWebRequest www = UnityWebRequest.Get(url);
    6.  
    7.         yield return www.SendWebRequest();
    8.         if (www.isHttpError || www.isNetworkError)
    9.         {
    10.             Debug.Log("Error while Receiving: " + www.error);
    11.         }
    12.         else
    13.         {
    14.             //Convert byte[] data of svg into string
    15.             string bitString = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
    16.             var tessOptions = new VectorUtils.TessellationOptions()
    17.             {
    18.                 StepDistance = 100.0f,
    19.                 MaxCordDeviation = 0.5f,
    20.                 MaxTanAngleDeviation = 0.1f,
    21.                 SamplingStepSize = 0.01f
    22.             };
    23.  
    24.             // Dynamically import the SVG data, and tessellate the resulting vector scene.
    25.             var sceneInfo = SVGParser.ImportSVG(new StringReader(bitString));
    26.             var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
    27.  
    28.             // Build a sprite with the tessellated geometry
    29.             Sprite sprite = VectorUtils.BuildSprite(geoms, 10.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
    30.             svgimg.sprite = sprite;
    31.         }    
    32.     }