Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to use XML (Android Vector Drawable ) for images on Android and SVG for IOS?

Hi
I currently use XML (android vector drawables) for images in the resources/drawable folder for Android.
That works fine.
I want to use SVG's for IOS however when i place SVG's inside the resources folder with the same file name, it doesn't work. PNG's work fine. but i want to use SVG's as they are higher quality.
I've also tried using FFsvgcachedimage but that stops android from working but IOS then works fine.
Has anyone implemented SVG's and Android Vectors in Xamarin forms before?
Thanks

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    We could use SkiaSharp to load svg files directly in the Forms project.
    Firstly, put the file directly in the project with build action Embedded resource.
    And then create the load method like:

    private MemoryStream loadImage(string fileName, float width, float height)
    {
        var svg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(width, height));
        var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileName);
    
        svg.Load(stream);
        using (var bitMap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height))
        using (SKCanvas canvas = new SKCanvas(bitMap))
        {
            canvas.DrawPicture(svg.Picture);
            canvas.Flush();
            canvas.Save();
    
            using (SKImage image = SKImage.FromBitmap(bitMap))
            {
                using (SKData data = image.Encode(SKEncodedImageFormat.Png, 80))
                {
                    MemoryStream memStream = new MemoryStream();
                    data.SaveTo(memStream);
                    memStream.Seek(0, SeekOrigin.Begin);
                    return memStream;
                }
            }
        }
    }
    

    Use it like:

    Image.Source = ImageSource.FromStream(() => loadImage("SvgSample.sample.svg", 50, 50));
    

    Do not forget to add the project name as the prefix.
    To use skiasharp, install the packages below:

Sign In or Register to comment.