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

求助:无法修改GraphicsView控件的背景颜色

MAUI GraphicsView 无法修改背景颜色的解决方案

GraphicsView的视觉内容完全由绑定的Drawable负责绘制,控件本身的Background/BackgroundColor属性在MAUI中不会生效,你需要在Drawable的Draw方法里主动填充整个控件区域来设置背景色。

修改步骤:

  • 移除XAML中GraphicsView的Background和BackgroundColor属性(这些属性对GraphicsView无效)
  • 在Draw方法开头,先填充整个控件的区域作为背景

修改后的代码:

XAML

<VerticalStackLayout>
    <Border StrokeThickness="0">
        <GraphicsView x:Name="canvas" 
                      Drawable="{StaticResource drawable}"
                      HeightRequest="500"
                      WidthRequest="500"/>
    </Border>
</VerticalStackLayout>    

C# 代码后台

public void Draw(ICanvas canvas, RectF dirtyRect)
{
    // 填充整个GraphicsView的区域作为背景
    canvas.FillColor = Colors.Yellow;
    canvas.FillRectangle(dirtyRect);

    // 绘制文本内容
    canvas.FontColor = Colors.Red;
    canvas.FontSize = 18;
    canvas.DrawString("Text is left aligned.", 50, 20, 380, 100, HorizontalAlignment.Left, VerticalAlignment.Top);
    canvas.DrawString("Text is centered.", 20, 60, 380, 100, HorizontalAlignment.Center, VerticalAlignment.Top);
    canvas.DrawString("Text is right aligned.", 20, 100, 380, 100, HorizontalAlignment.Right, VerticalAlignment.Top);
}

原因说明:

GraphicsView是基于Canvas的轻量级绘制控件,它本身不负责渲染背景,所有视觉元素都需要通过Drawable的Draw方法绘制。你之前的代码仅设置了FillColor但没有调用FillRectangle来填充控件范围,所以背景色无法显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:53:27