WPF中的画刷比GDI+中要强大得多,除了常用的实心画刷、渐变画刷外,还支持更多的平铺画刷,这包括DrawingBrush、ImageBrush、VisualBrush,其中DrawingBrush使得我们可以将自定义的绘制用于任何可以使用普通画刷的地方。
在WPF中自定义你的绘制(五)
周银辉
将我们的绘制转变为画刷
WPF中的画刷比GDI+中要强大得多,除了常用的实心画刷、渐变画刷外,还支持更多的平铺画刷,这包括DrawingBrush、ImageBrush、VisualBrush,其中DrawingBrush使得我们可以将自定义的绘制用于任何可以使用普通画刷的地方。
比如下面的代码,我们将自定义一个椭圆和一个矩形,然后将它们合并成一个图形并将
改图形用作窗口的背景画刷:
public Window1()

{
InitializeComponent();


//background
EllipseGeometry ellipse = new EllipseGeometry(new Point(50, 50), 50, 20);
RectangleGeometry rect = new RectangleGeometry(new Rect(50, 50, 50, 20), 5, 5);
PathGeometry combin = Geometry.Combine(ellipse, rect, GeometryCombineMode.Xor, null);
GeometryDrawing drawing = new GeometryDrawing(Brushes.LightBlue, new Pen(Brushes.Green, 2), combin);

DrawingBrush background = new DrawingBrush(drawing);
this.Background = background;


}运行效果如下:

也许将整个图形填充于整个区域并不是我们想要的结果,没关系,我们可以通过设置视口(Viewport)和平铺方式(TileMode)来调整图形的平铺效果。

Viewport为我们指示了如何将图形投射到绘制表面,如果我们将绘制表面的左上角定义为(0,0),右下角定义我(1,1),那么可以设置一个相当与该值的矩形(Rect)来指示我们的图形应该被投射到哪里。比如Rect(0,0,0.5,0.5)则表示在绘制表面的左上角开始的长宽均为绘制表面1/2的矩形区域。这样的矩形Rect(0,0,0.5,0.5)就是我们所说的视口(这与3D中的视口类似)。所以要得到上图的效果,我们只需要这样设置我们的DrawingBrush就可以了:
background.Viewport = new Rect(0, 0, 0.15, 0.15);
background.TileMode = TileMode.Tile;此外,DrawingBrush还有一个很有意思的属性ViewBox(继承于TileBrush),它指示了只取图形中的哪一部分作为观察区域(这与Clip不同),它的定义方式与Viewport类似,但它不是相对于绘制表面而是相当于我们的图形的。
SDK中是这样解释ViewBox的:

参考下面的代码,我们仅仅取了整个绘制的图形的1/4(整个图形的左下部分)并将其作为窗口的的背景画刷:
public Window1()

{
InitializeComponent();


//background
EllipseGeometry ellipse = new EllipseGeometry(new Point(50, 50), 50, 20);
RectangleGeometry rect = new RectangleGeometry(new Rect(50, 50, 50, 20), 5, 5);
PathGeometry combin = Geometry.Combine(ellipse, rect, GeometryCombineMode.Xor, null);
GeometryDrawing drawing = new GeometryDrawing(Brushes.LightBlue, new Pen(Brushes.Green, 2), combin);

DrawingBrush background = new DrawingBrush(drawing);
background.Viewbox = new Rect(0.5, 0.5, 0.5, 0.5);
this.Background = background;


}
效果图如下:

此外,值得一提的是,Viewport和Viewbox除了使用相对值外,你也可以使用绝对坐标值,不过你需要将ViewportUnits属性和ViewboxUnit属性由BrushMappingMode.RelativeToBoundingBox修改为BrshMappingMode.Absolute。