1.画刷简介
画刷的基类是 System.Windows.Media.Brush。 根据实现效果的不同有3种画刷:画刷 简介
SolidColorBrush 单色画刷
CardientBrush 渐变色画刷。包括LinearGradinentBrush 和 BadialGradientBrush 两种,分别实现线性渐变和放射性渐变效果。
ImageBrush 使用位图作为画刷 。
2. SolidColorBrush
SolidColorBrush 用于使用固定颜色为指定区域着色。使用时, 可以使用系统预定义的颜色画刷,例如Red。或者可以创建一个新的画刷并且使用RGB等参数指定新的颜色。
例如:
<Grid x:Name="ContentPanel" Grid.Row="1"> <Grid.Background> <SolidColorBrush Color="Blue" /> </Grid.Background>
</Grid>以上代码等同于:<Grid x:Name="ContentPanel" Grid.Row="1" Background="Blue">
上面代码中Color 值和SolidColorBrush是上面关系?上面的Background实际上是 ContentPanel.Background 属性, 用于设置或者获取一个用于填充的Brush 类型值。它的定义是:public
Brush Background {get; set; }以上代码实质上是:SolidColorBrush brush = new SolidColorBrush();
brush.Color = Colors.Blue;
ContentPanel.Background = brush; 因此,在XAML中直接使用“Blue”为Background 属性赋值,实际上是使用系统预定义的一种 SolidColorBrush (其Color 属性为Colors.Blue)为Backgound 赋值。 除了预定义值外, SolidColorBrush 还可以使用自定义的属性值。例如使用ARGB 值: <SolidColorBrush >
<SolidColorBrush.Color >
<Color A="255" R="0" G="0" B="255"/>
</SolidColorBrush.Color>
</SolidColorBrush> 除了Color 属性之外, SolidColorBrush 常用属性还包括Opacity 透明度: <SolidColorBrush Opacity="0.5" /> 3. CardientBrushCardientBrush 可以在指定区域中绘制出颜色渐变效果。 LinearGradientBrush 是线性渐变填充,使用 LinearGradientBrush 需要设置渐变坐标:起点坐标StartPoint 和终点坐标EndPoint,
坐标值的范围是从0~1之间的值,坐标表示在指定区域中的相对位置。不同的颜色使用 GradientStop 来设置。同时需要指定每一个GradientStop 的相对位置(偏移量), 例如: <Grid x:Name="LayoutRoot" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.Background >
<LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
<GradientStop Color="Red" Offset="0.2"/>
<GradientStop Color="Blue" Offset="0.5" />
<GradientStop Color="Green" Offset="0.8" />
</LinearGradientBrush>
</Grid.Background> </Grid>三种颜色的中心位置是代码中指定的GradientStop 的Offset。 而代码:StartPoint="0,0" EndPoint="1,0" 则指定渐变是发生在横轴。4. RadialGradientBrushRadialGradientBrush 可以用来实现放射性渐变,可以使用 Center属性指定图形中心点,GradientOrigin属性用来定义放射点的相对位置坐标, RadiusX 和ARadiusY 分别指定在X轴和Y轴上的放射半径。可以使用多个
GradientStop 定义颜色的相对位置。 以下是一个例子: <Canvas Grid.Row="2" Height="200" Width="120">
<Canvas.Background>
<RadialGradientBrush Center="0.5 0.5" GradientOrigin="0.5 0.5" >
<GradientStop Color="Brown" Offset="0.3" />
<GradientStop Color="Blue" Offset="0.6" />
<GradientStop Color="Green" Offset="1" />
</RadialGradientBrush>
</Canvas.Background>
</Canvas>5. ImageBrush ImageBrush 可以将位图作为画刷的元素在指定区域填充。使用时需要指定 ImagesSource 属性: <ImageBrush ImageSource = "Images/Penguins.jpg" />