You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui中如何根据条件动态指定SVG图像的颜色?

.NET MAUI 动态设置SVG图像颜色的可行方案

方法1:通过SkiaSharp手动加载并着色SVG

SkiaSharp对SVG的处理灵活性更高,能轻松实现动态着色需求:

  1. 安装NuGet包:SkiaSharp.Views.Maui 和 SkiaSharp.Extended.Svg
  2. 在XAML中添加用于渲染的画布控件:
<skia:SKCanvasView x:Name="SvgCanvas" PaintSurface="OnSvgCanvasPaintSurface" />
  1. 后台代码加载SVG并动态设置颜色:
private void OnSvgCanvasPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
    var canvas = e.Surface.Canvas;
    canvas.Clear();

    // 加载SVG文件(确保文件放在Resources/Raw目录,生成操作设为MauiAsset)
    using var stream = FileSystem.OpenAppPackageFileAsync("your-svg-file.svg").Result;
    var svg = new SKSvg();
    svg.Load(stream);

    // 根据业务条件动态设置颜色
    var targetColor = SomeCondition ? Colors.Red : Colors.Blue;
    var paint = new SKPaint
    {
        Color = targetColor.ToSKColor(),
        Style = SKPaintStyle.Fill
    };

    // 计算缩放比例,让SVG适配画布大小
    var scale = Math.Min(e.Info.Width / svg.Picture.CullRect.Width, e.Info.Height / svg.Picture.CullRect.Height);
    canvas.Scale(scale);

    // 绘制带指定颜色的SVG
    canvas.DrawPicture(svg.Picture, ref paint);
}

需要更新颜色时,修改targetColor后调用SvgCanvas.InvalidateSurface()即可触发重新渲染。

方法2:自定义可绑定颜色的SVG控件

基于官方SVG封装自定义控件,适配MVVM绑定场景:

  1. 创建自定义控件类:
public class TintableSvgImage : Image
{
    public static readonly BindableProperty TintColorProperty =
        BindableProperty.Create(nameof(TintColor), typeof(Color), typeof(TintableSvgImage), Colors.Black, propertyChanged: OnTintColorChanged);

    public Color TintColor
    {
        get => (Color)GetValue(TintColorProperty);
        set => SetValue(TintColorProperty, value);
    }

    private static void OnTintColorChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var image = (TintableSvgImage)bindable;
        if (image.Source is SvgImageSource svgSource)
        {
            // 重新创建SVG源并应用新的着色
            image.Source = new SvgImageSource
            {
                Resource = svgSource.Resource,
                TintColor = (Color)newValue
            };
        }
    }
}
  1. 在XAML中使用该控件并绑定颜色属性:
<local:TintableSvgImage Source="resource://YourAppName.Resources.Images.your-svg-file.svg" 
                        TintColor="{Binding CurrentDisplayColor}" />

当ViewModel中的CurrentDisplayColor属性变化时,SVG颜色会自动同步更新。

注意事项

  • 确保SVG文件的生成操作设置为MauiAsset,否则无法正常加载
  • 如果SVG包含多色图层,SkiaSharp方法支持给不同路径单独设置颜色,灵活性更强
  • 自定义控件方法更贴合MVVM开发模式,适合需要数据绑定的场景

内容的提问来源于stack exchange,提问作者Jasper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:31:01