你並不需要用WPF「畫」任何東西。如果要繪製線條,請使用適當的幾何圖形繪製線條。
在你的情況下,它可能很簡單。你只是繪製一個網格,所以你可以創建一個DrawingBrush
來繪製一個單一的網格正方形,並將其平鋪以填充其餘部分。要繪製您的圖塊,您可以將其視爲繪製X的。所以有一個20x10
瓦(相當於stepX
和stepY
):
(PS,斜率slop
是多餘的,因爲你已經擁有水平和垂直步長)
<DrawingBrush x:Key="GridTile" Stretch="None" TileMode="Tile"
Viewport="0,0 20,10" ViewportUnits="Absolute">
<!-- ^^^^^^^^^^^ set the size of the tile-->
<DrawingBrush.Drawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<!-- draw a single X -->
<GeometryGroup>
<!-- top-left to bottom-right -->
<LineGeometry StartPoint="0,0" EndPoint="20,10" />
<!-- bottom-left to top-right -->
<LineGeometry StartPoint="0,10" EndPoint="20,0" />
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<!-- set color and thickness of lines -->
<Pen Thickness="1" Brush="Black" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
這需要繪圖的護理線。現在爲了能夠從邊緣繪製它們在網格中的偏移量,您需要使用另一個畫筆繪製具有所需尺寸的矩形,並用瓦片填充。所以有(30, 45)
(對應於startX
和startY
)與width
和height
起始位置,130x120
:
<DrawingBrush x:Key="OffsetGrid" Stretch="None" AlignmentX="Left" AlignmentY="Top">
<DrawingBrush.Transform>
<!-- set the left and top offsets -->
<TranslateTransform X="30" Y="45" />
</DrawingBrush.Transform>
<DrawingBrush.Drawing>
<GeometryDrawing Brush="{StaticResource GridTile}" >
<GeometryDrawing.Geometry>
<!-- set the width and height filled with the tile from the origin -->
<RectangleGeometry Rect="0,0 130,120" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
後來終於用它,只是把它設置爲網格的背景(或其他面板) :
<Grid Background="{StaticResource OffsetGrid}">
<!-- ... -->
</Grid>
下面是它的最終看起來像:
如果要動態地生成刷,這裏的基於上述XAML等效功能:
static Brush CreateGridBrush(Rect bounds, Size tileSize)
{
var gridColor = Brushes.Black;
var gridThickness = 1.0;
var tileRect = new Rect(tileSize);
var gridTile = new DrawingBrush
{
Stretch = Stretch.None,
TileMode = TileMode.Tile,
Viewport = tileRect,
ViewportUnits = BrushMappingMode.Absolute,
Drawing = new GeometryDrawing
{
Pen = new Pen(gridColor, gridThickness),
Geometry = new GeometryGroup
{
Children = new GeometryCollection
{
new LineGeometry(tileRect.TopLeft, tileRect.BottomRight),
new LineGeometry(tileRect.BottomLeft, tileRect.TopRight)
}
}
}
};
var offsetGrid = new DrawingBrush
{
Stretch = Stretch.None,
AlignmentX = AlignmentX.Left,
AlignmentY = AlignmentY.Top,
Transform = new TranslateTransform(bounds.Left, bounds.Top),
Drawing = new GeometryDrawing
{
Geometry = new RectangleGeometry(new Rect(bounds.Size)),
Brush = gridTile
}
};
return offsetGrid;
}
非常感謝!你的代碼是完美的! – Renaud
這段代碼絕對是真棒,感謝分享,但對於動態創建它的c#等價代碼,我只是有一些問題 - 由於抽象類繼承問題,我似乎無法使用此創建畫筆。只是好奇你將如何通過這種方法創建一個? – WearyWanderer