画刷用于填充区域,不管是元素的背景色、前景色以及边框,还是形状的内部填充和笔画(stroke)。
-
画刷支持更改通知,因为它们继承自Freezable类。如果改变了画刷,任何使用画刷的元素都会自动更新绘制自身。
-
画刷支持部分透明。为此,只需要修改Opacity属性,使背景能够透过前面的内容进行显示。
-
通过SystemBrushes类可以访问这样的画刷:此类画刷使用Windows系统设置为当前计算机定义的首选颜色。
画刷类继承自System.Windows.Media.Brush的类。
名称 | 说明 |
---|---|
SolidColorBrush | 使用单一的连续颜色绘制区域 |
LinerGradientBrush | 使用渐变填充绘制区域,渐变的阴影填充从一种颜色变化到另一种颜色(并且,也可以再变化到第三种颜色之后再变化到第4中颜色,以此类推) |
RadialGradientBrush | 使用径向渐变填充绘制区域,除了是在圆形模式中从中心点向外部辐射渐变之外,这种画刷和线性渐变画刷类似。 |
ImageBrush | 使用可被拉伸、缩放和平铺的图像绘制区域 |
DrawingBrush | 使用Drawing对象绘制区域,该对象可以包含已经定义的形状和位图 |
VisualBrush | 使用Visual对象绘制区域。因为所有WPF元素都继承自Visual类,所以可使用该画刷将部分用户界面复制到另一个区域。当创建特殊效果时,比如部分反射效果,该画刷特别有用。 |
BitmapCacheBrush | 使用从Visual对象缓存的内容绘制区域。这种画刷和Visual画刷类型,但如果在多个地方重用图形内容或者频繁地重绘图形内容,这种画刷更高效。 |
SolidColorBrush画刷
SolidColorBrush brush = null;
brush = System.Windows.Media.Brushes.Transparent;//使用System.Windows.Media.Brushes类
brush = System.Windows.SystemColors.HighlightBrush;//使用System.Windows.SystemColors类
//使用SolidColorBrush类构造,需要一个Color对象
//Color对象可以从System.Windows.Media.Colors得到,也可以使用RGBA自定义一个Color对象
brush = new SolidColorBrush(System.Windows.Media.Colors.Red);
brush = new SolidColorBrush(new Color() { R = 0xff, G = 0xff, B = 0xff, A = 0xff });
ImageBrush画刷
可通过ImageBrush画刷使用位图填充区域。可使用最常见的文件类型,包括BMP、PNG、GIF、JPEG等文件。可通过设置ImageSource属性来指定希望使用的图像。
ImageBrush.ImageSource属性和Image元素的Source属性的工作方式相同,这意味着也可以使用指向资源、外部文件或Web站点的URI设置ImageSource属性。也可以为ImageSource属性提供DrawingImage对象,创建使用由XAML定义的矢量内容的ImageBrush画刷。可通过这种方式降低开销。
<Canvas.Background>
<ImageBrush ImageSource="logo.png"/>
</Canvas.Background>
ImageBrush还有Viewport、ViewportUnits与TileMode属性,这三个属性决定了平铺图像的尺寸和排列方式。
VisualBrush画刷
VisualBrush画刷不常用,使用这种画刷获取元素的可视化内容,并使用该内容填充任意表面。例如,可使用VisualBrush画刷将窗口中某一个按钮的外观复制到同一窗口中的其他位置。然而,复制的按钮不能被单击,也不能通过任何方式与其进行交互。在此只是复制了元素的外观。
<Path
x:Name="aa"
Data="M 50,50 A 50,50,270,1,1,100,0 H 150 A 50,50,270,1,1,200,50 L 200,150 L 50,150 Z"
Fill="Red"
Stroke="Black" />
<GroupBox>
<GroupBox.Background>
<VisualBrush Visual="{Binding ElementName=aa}" />
</GroupBox.Background>
</GroupBox>
<StackPanel.Background>
<VisualBrush Opacity="0.1" Viewport="0,0,250,30" ViewportUnits="Absolute" TileMode="Tile" Stretch="None">
<VisualBrush.Visual>
<Border Width="250" Background="Transparent">
<TextBlock Margin="5" FontFamily="Palatino Linotype" FontSize="20px" >
Painting with VisualBrush
<TextBlock.Foreground>
<LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.0" Color="Black" />
<GradientStop Offset="1.0" Color="Blue" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</TextBlock.Foreground>
</TextBlock>
</Border>
</VisualBrush.Visual>
<VisualBrush.RelativeTransform>
<RotateTransform Angle="0" CenterX="0.5" CenterY="0.5" />
</VisualBrush.RelativeTransform>
</VisualBrush>
</StackPanel.Background>