Home > other >  Specify the color of a SVG image in .NET Maui
Specify the color of a SVG image in .NET Maui

Time:11-09

.NET MAUI has the ability to use SVG images which is really nice, but I haven't been able to set the color of the SVG image. The official docs state I could use the TintColor in the project file but that's not a good solution as I want to be able to use different colors depending on certain conditions. So can we somehow specify the color of a SVG image?

CodePudding user response:

Maybe you could use skiasharp. I give some examples.

First add Nuget, such as SkiaSharp.Views.Maui.Controls, SkiaSharp.Svg.

In the xaml, define a SKCanvasView. The PaintSurface event handler is where you do all your drawing.

<StackLayout>
    <skiact:SKCanvasView  WidthRequest="500" HeightRequest="500" x:Name="mycanvasview" PaintSurface="mycanvasview_PaintSurface">
    </skiact:SKCanvasView>
</StackLayout>

In the .cs file, implement mycanvasview_PaintSurface method. Add some code like this:

private void mycanvasview_PaintSurface(object sender, SkiaSharp.Views.Maui.SKPaintSurfaceEventArgs e)
{
    SKImageInfo info = e.Info;
    SKSurface surface = e.Surface;
    SKCanvas canvas = surface.Canvas;

    canvas.Clear();
    Stream stream = LoadStream(typeof(MainPage),"myfile.svg");
    SKSvg svg = new SKSvg();
    svg.Load(stream);

    using (var paint = new SKPaint())
    {
        paint.ColorFilter = SKColorFilter.CreateBlendMode(
            SKColors.Yellow,      
            SKBlendMode.SrcIn); 
        canvas.DrawPicture(svg.Picture ,paint);
    }
}


private static Stream LoadStream(Type type, string v)
{
    Assembly assembly = type.GetTypeInfo().Assembly;
    Stream stream = assembly.GetManifestResourceStream(v);
    return stream;
}

You svg file will change the color.

I hope my answer could help you.

CodePudding user response:

I just figured out that the Maui Community toolkit has a IconTintColorBehavior that does just want I want.

Usage:

<Image Source="shield.png">
    <Image.Behaviors>
        <toolkit:IconTintColorBehavior TintColor="Red" />
    </Image.Behaviors>
</Image>
  • Related