Search Unity

Question How to get SVGParser.ImportSVG to correctly preserve viewport

Discussion in '2D' started by twn9009, May 9, 2023.

  1. twn9009

    twn9009

    Joined:
    May 2, 2019
    Posts:
    58
    hi
    im having trouble with the SVGParser.ImportSVG() method, if i import the svg directly into my assets and use the SVG importer's viewport options - preserve viewport option it correctly sets the origin of the svg as seen below.



    however if i do it via code using the SVGParser.ImportSVG() method no matter the viewport options i use it always puts the origin of the svg in the middle as seen below



    not sure if im setting the methods up correctly or if im building the sprite incorrectly, any help would be greatly appreciated
    Code (CSharp):
    1.    var tessOptions = new VectorUtils.TessellationOptions()
    2.         {
    3.             StepDistance = 100.0f,
    4.             MaxCordDeviation = 0.5f,
    5.             MaxTanAngleDeviation = 0.1f,
    6.             SamplingStepSize = 0.01f
    7.         };
    8.  
    9.      
    10.         var sceneInfo = SVGParser.ImportSVG(new StringReader(svg),ViewportOptions.PreserveViewport);
    11.  
    12.         var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
    13.  
    14.         Debug.Log(svgXML.name + " " + svg);
    15.        
    16.         var sprite = VectorUtils.BuildSprite(geoms, 10.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
    17.         return sprite;
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,751
    I would look more at line 16 where you tell it to make the sprite with
    VectorUtils.Alignment.Center


    Caveat: I haven't used any of the above APIs but that's just the first obvious thing to check.
     
  3. twn9009

    twn9009

    Joined:
    May 2, 2019
    Posts:
    58
    thanks for the reply, already tried all the alignment settings and it didn't make much difference in this case, the svg has a very specific viewbox needed for perfectly aligning with another image so the alignment needs to be set to center still, i've set everything the same in code as it is in the importer, still unsure why its doing it but thanks for trying anyways
     
  4. twn9009

    twn9009

    Joined:
    May 2, 2019
    Posts:
    58
    i figured it out, there is a second build sprite method that takes a rect, just had to parse the width and height manually from the xml string using regex to get the rect, the editor will do it automatically in the svg importer, @"width=""([\d.]+)""" is the regex for svg xml if anyone needs it in future
     
    Kurt-Dekker likes this.