Skip to content

Instantly share code, notes, and snippets.

@punker76
Created April 8, 2020 20:13
Show Gist options
  • Save punker76/67bd048ff403c1c73737905183f819a9 to your computer and use it in GitHub Desktop.
Save punker76/67bd048ff403c1c73737905183f819a9 to your computer and use it in GitHub Desktop.
SkiaSharp Svg to Png
// memoryStream is the stream of the svg url
// imageStream is the converted png which will be converted with Splat.BitmapLoader to an IBitmap
var svg = new SkiaSharp.Extended.Svg.SKSvg();
svg.Load(memoryStream);
var imageInfo = new SKImageInfo((int)desiredSize.Width, (int)desiredSize.Height);
using (var surface = SKSurface.Create(imageInfo))
using (var canvas = surface.Canvas)
{
// calculate the scaling need to fit to screen
var scaleX = desiredSize.Width / svg.Picture.CullRect.Width;
var scaleY = desiredSize.Height / svg.Picture.CullRect.Height;
var matrix = SKMatrix.MakeScale((float)scaleX, (float)scaleY);
// draw the svg
canvas.Clear(SKColors.Transparent);
canvas.DrawPicture(svg.Picture, ref matrix);
canvas.Flush();
using (var data = surface.Snapshot())
using (var pngImage = data.Encode(SKEncodedImageFormat.Png, 100))
{
pngImage.SaveTo(imageStream);
}
}
@laggage
Copy link

laggage commented May 4, 2023

Additional information:

Nuget package SkiaSharp.Svg is required

@abelopez-benchmark
Copy link

I love you man, you saved me! ❤️, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment