这可能是一个琐碎的问题:我需要用棋盘格图案填充一个矩形,其中每个单元格大小为1x1像素。如何在XAML中创建此模式的矢量几何图形?我没有使用Blend,而是手工制作我的矢量图形。
谢谢 Konstantin
以下是从下面的XAML中获取到的内容:
. .
这里是XAML的详细版本,描述了正在创建的几何形状。 RectangleGeometry 元素的 Rect 属性接受一个 left、top、width 和 height 序列。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="250">
<Canvas>
<Rectangle Width="100" Height="100" Canvas.Left="10" Canvas.Top="10">
<Rectangle.Fill>
<DrawingBrush Stretch="None" TileMode="Tile" Viewport="0,0,2,2" ViewportUnits="Absolute">
<!-- a drawing of 4 checkerboard tiles -->
<DrawingBrush.Drawing>
<DrawingGroup>
<!-- checkerboard background -->
<GeometryDrawing Brush="White">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,2,2" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<!-- two checkerboard foreground tiles -->
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<GeometryGroup>
<RectangleGeometry Rect="0,0,1,1" />
<RectangleGeometry Rect="1,1,1,1" />
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
</Canvas>
</Window>
以下较短的版本呈现了完全相同的图像,但使用几何图形的速记符号。 棋盘格瓦片被渲染为路径。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="250">
<Canvas>
<Rectangle Width="100" Height="100" Canvas.Left="10" Canvas.Top="10">
<Rectangle.Fill>
<DrawingBrush Stretch="None" TileMode="Tile" Viewport="0,0,2,2" ViewportUnits="Absolute">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Geometry="M0,0 L2,0 2,2, 0,2Z" Brush="White"/>
<GeometryDrawing Geometry="M0,1 L2,1 2,2, 1,2 1,0 0,0Z" Brush="Black"/>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
</Canvas>
</Window>
注意:此方法适用于矩形在整数坐标上的情况。如果矩形位于分数坐标(例如Canvas.Left="10.5"而不是"10"),则笔刷会出现反锯齿,失去清晰的图案。SnapToDevicePixels无济于事。只要矩形位置已知,您可以设置DrawingBrush的RelativeTransform来偏移小数部分,以避免反锯齿。
<DrawingBrush TileMode="Tile" Viewport="0,0,32,32" ViewportUnits="Absolute">
<DrawingBrush.Drawing>
<GeometryDrawing Geometry="M0,0 H1 V1 H2 V2 H1 V1 H0Z" Brush="LightGray"/>
</DrawingBrush.Drawing>
</DrawingBrush>
M0,0 H1 V1 H2 V2 H1 V1 H0Z
:) - TorbenJ