7

.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?

Jasper
  • 545
  • 7
  • 18

2 Answers2

14

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>

namespace

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Jasper
  • 545
  • 7
  • 18
1

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.

Liqun Shen-MSFT
  • 3,490
  • 2
  • 3
  • 11