在.NET MAUI里,brushes是用来填充控件背景或前景的核心工具,而GradientBrush作为抽象基类,派生了线性渐变和径向渐变两种实用笔刷。借助它们,我们可以用纯XAML或C#代码写出自然的色彩过渡背景,而不必依赖图片资源。

GradientBrush的两种常见派生类型
MAUI自带的渐变笔刷主要包含下面两类:
- LinearGradientBrush:沿一条直线方向进行颜色插值,适合做水平、垂直或斜向渐变。
- RadialGradientBrush:从圆心向外放射状渐变,常用于高光或聚焦效果。
用XAML定义线性渐变背景
最常见的做法是在页面或控件的Background属性中直接写入LinearGradientBrush,并通过GradientStop指定色标。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DemoApp.MainPage">
<ContentPage.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="SkyBlue" Offset="0.0" />
<GradientStop Color="MidnightBlue" Offset="1.0" />
</LinearGradientBrush>
<ContentPage.Background>
<VerticalStackLayout>
<Label Text="MAUI渐变背景示例" TextColor="White" />
</VerticalStackLayout>
</ContentPage>
在C#代码中创建渐变笔刷
如果界面逻辑需要根据运行状态切换背景,可以用代码构造GradientBrush对象再赋值给Background属性。
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
public class MyPage : ContentPage
{
public MyPage()
{
// 创建线性渐变笔刷
var brush = new LinearGradientBrush
{
StartPoint = new Point(0, 0),
EndPoint = new Point(1, 0)
};
brush.GradientStops.Add(new GradientStop(Colors.Orange, 0.0f));
brush.GradientStops.Add(new GradientStop(Colors.Red, 1.0f));
this.Background = brush;
Content = new Label
{
Text = "代码方式渐变",
TextColor = Colors.White
};
}
}
径向渐变的基本写法
RadialGradientBrush通过Center、Radius控制圆心和半径,同样使用GradientStop描述颜色分布。
<Border WidthRequest="200" HeightRequest="200">
<Border.Background>
<RadialGradientBrush Center="0.5,0.5" Radius="0.5">
<GradientStop Color="Yellow" Offset="0.0" />
<GradientStop Color="DarkOrange" Offset="1.0" />
</RadialGradientBrush>
</Border.Background>
</Border>
使用注意事项
| 要点 | 说明 |
|---|---|
| Offset范围 | GradientStop的Offset取值为0到1,表示渐变方向上的相对位置 |
| 坐标系统 | StartPoint和EndPoint使用相对坐标,0到1之间,左上角为0,0 |
| 性能 | 相比静态图片,GradientBrush由GPU绘制,内存占用更低 |
通过上述示例可以看到,MAUI的brushes体系让渐变背景的定义变得直观且灵活。无论是用XAML静态声明还是C#动态切换,GradientBrush都能满足大多数跨平台界面的色彩过渡需求。
MAUIGradientBrushbrushes修改时间:2026-07-29 20:21:20