五 使用绘图绘制
DrawingBrush使用绘制区域 Drawing 。 Drawing可以包含形状、图像、文本和媒体。 下面的示例使用 DrawingBrush 绘制 Fill 的 Rectangle 。
使用 System.windows.media.drawingbrush> 绘制的矩形
C#:
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfApplication
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//实例化矩形并设置宽度和高度
Rectangle exampleRectangle = new Rectangle();
exampleRectangle.Width = 75;
exampleRectangle.Height = 75;
// 创建一个DrawingBrush并使用它
DrawingBrush myBrush = new DrawingBrush();
// (1)绘制
/*
参数:
brush:
用于填充此 System.Windows.Media.GeometryDrawing 的画笔。
pen:
用于绘制此 System.Windows.Media.GeometryDrawing 的钢笔。
geometry:
几何图形
*/
GeometryDrawing backgroundSquare =
new GeometryDrawing(
Brushes.White,
null,
new RectangleGeometry(new Rect(0, 0, 100, 100)));
//复合几何图形
GeometryGroup aGeometryGroup = new GeometryGroup();
aGeometryGroup.Children.Add(new RectangleGeometry(new
Rect(0, 0, 50, 50)));
aGeometryGroup.Children.Add(new RectangleGeometry(new
Rect(50, 50, 50, 50)));
//使用线性渐变绘制区域
LinearGradientBrush checkerBrush = new
LinearGradientBrush();
checkerBrush.GradientStops.Add(new
GradientStop(Colors.Black, 0.0));
checkerBrush.GradientStops.Add(new
GradientStop(Colors.Gray, 1.0));
// (2)绘制
GeometryDrawing checkers = new
GeometryDrawing(checkerBrush, null, aGeometryGroup);
//绘图集合:把(1)绘制和(2)绘制添加到集合里面
DrawingGroup checkersDrawingGroup = new DrawingGroup();
checkersDrawingGroup.Children.Add(backgroundSquare);
checkersDrawingGroup.Children.Add(checkers);
myBrush.Drawing = checkersDrawingGroup;
myBrush.Viewport = new Rect(0, 0, 0.25, 0.25);
myBrush.TileMode = TileMode.Tile;
//设置填充
exampleRectangle.Fill = myBrush;
//把矩形添加到GD_Main里面
GD_Main.Children.Add(exampleRectangle);
}
}
}
XAML:
<Rectangle Width="75" Height="75">
<Rectangle.Fill>
<DrawingBrush Viewport="0,0,0.25,0.25" TileMode="Tile">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="White">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,100,100" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<GeometryGroup>
<RectangleGeometry Rect="0,0,50,50" />
<RectangleGeometry Rect="50,50,50,50" />
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Brush>
<LinearGradientBrush>
<GradientStop Offset="0.0" Color="Black" />
<GradientStop Offset="1.0" Color="Gray" />
</LinearGradientBrush>
</GeometryDrawing.Brush>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
效果图: