user1210708
user1210708

Reputation: 523

SVG WPF C# Rendering Issue

While starting with the SVG Rendering Library 1.7.0 (installed using NuGet) I get an issue that just does not make sense to me. Using the simplest of SVG content (a filled rectangle with clearly recognizable black border):

<svg  xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="0" y="0" height="50" width="50"
          style="stroke:#000000; fill: #efefef"/>
</svg>

I then proceed to load and display it using a bitmap and a picture box:

        String path = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory,
            "etc\\simple.svg");

        var svgDocument = SvgDocument.Open(path);
        bitmap = new Bitmap(50, 50, PixelFormat.Format32bppArgb);
        svgDocument.Draw(bitmap);
        var ms = new MemoryStream();
        bitmap.Save(ms, ImageFormat.Png);
        ms.Position = 0;

        var bi = new BitmapImage();
        bi.BeginInit();
        bi.StreamSource = ms;
        bi.EndInit();

        img.Source = bi;

So, rendering a 50 by 50 rectangle to a 50 by 50 bitmap should render me a non-scaled full image consisting of a gray square surrounded by a black border. What however happens is that the top and left sides of the border is cut off.

Conceptually I am obviously missing something, as playing with the bitmap size, view port and scaling give me mixed results, one or two working but without any understanding to it.

Here is the amended source that works - tested - thanks to Robert's suggestion: bitmap = new Bitmap(51, 51, PixelFormat.Format32bppArgb);

        svgDocument.Transforms.Add(new SvgTranslate(.5f, .5f));
        svgDocument.Draw(bitmap);

Thanks, Gawie

Upvotes: 1

Views: 1686

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

Strokes are drawn 1/2 inside and 1/2 outside the edge so the stroke you are drawing is partially cut off at the edges because your shape is actually 1/2 (the left edge stroke) + 50 + 1/2 (the right edge stroke) = 51 units wide, similarly its also 51 units high.

You could position the rect at 0.5, 0.5 and either make it smaller or make the bitmap larger to display it completely.

The SVG specification says

The ‘stroke’ property paints along the outline of the given graphical element.

Upvotes: 2

Related Questions