SKSvg set size

UnexpectedPirateUnexpectedPirate RUMember ✭✭

Hi all

I'm trying to draw svg on the SKCanvasView, but I don't know how to set picture size like in the SKCanvas.DrawImage method. Here is my code:

canvasView = new SKCanvasView();
canvasView.PaintSurface += (sender, e) =>
        {
                ibyte[] bytes = Encoding.UTF8.GetBytes(svgString);
                MemoryStream stream = new MemoryStream(bytes);
                SKSvg svg = new SKSvg(/*canvasView.CanvasSize*/); // cuts, but not resizes
                svg.Load(stream);
                var canvas = e.Surface.Canvas;
                using (SKPaint paint = new SKPaint())
                {
                    canvas.Clear(Color.Transparent.ToSKColor());
                    canvas.DrawPicture(svg.Picture, paint);
                     // var img = SKImage.FromPicture(svg.Picture, new SKSizeI((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height)); // workaround, I don't like it
                    //canvas.DrawImage(img, SKRect.Create(canvasView.CanvasSize.Width, canvasView.CanvasSize.Height), paint);
                }
        }; 

Could someone suggest how to fit the svg picture into canvas size?

Thanks in advance!

Tagged:

Best Answer

  • mattleibowmattleibow ZAXamarin Team Xamurai
    Accepted Answer

    You have to draw with a SKMatrix. Here is a sample: https://github.com/mono/SkiaSharp/blob/master/samples/SkiaSharpSample.Shared/Samples/SvgSample.cs#L34-L39

    // get the size of the canvas
    float canvasMin = Math.Min(e.Info.Width, e.Info.Height);
    
    // get the size of the picture
    float svgMax = Math.Max(svg.Picture.CullRect.Width, svg.Picture.CullRect.Height);
    
    // get the scale to fill the screen
    float scale = canvasMin / svgMax;
    
    // create a scale matrix
    var matrix = SKMatrix.MakeScale(scale, scale);
    
    // draw the picture with the matrix
    canvas.DrawPicture(svg.Picture, ref matrix);
    

Answers

Sign In or Register to comment.