如何在WPF Canvas上绘制网格线?
我需要在 WPF 中的画布上构建一个绘制网格线的函数:
void DrawGridLine(double startX, double startY, double stepX, double stepY,
double slop, double width, double height)
{
// How to implement draw gridline here?
}
我该怎么做?
I need to build a function drawing gridline on the canvas in WPF:
void DrawGridLine(double startX, double startY, double stepX, double stepY,
double slop, double width, double height)
{
// How to implement draw gridline here?
}
How would I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上不必使用 WPF“绘制”任何内容。如果要绘制线条,请使用适当的几何图形来绘制它们。
就你而言,这可能真的很简单。您只是绘制一个网格,因此您可以创建一个
DrawingBrush
来绘制单个网格方块并将其平铺以填充其余部分。要绘制图块,您可以将其视为绘制 X。因此,要有一个20x10
图块(对应于stepX
和stepY
):(ps,斜率
slop
为多余的,因为你已经有了水平和垂直的步长)这负责绘制线条。现在,为了能够在网格中从边缘偏移绘制它们,您需要使用另一个画笔,在其中绘制具有所需尺寸的矩形,并填充瓷砖。因此,起始位置为
(30, 45)
(对应于startX
和startY
),宽度为和
height
、130x120
:最后要使用它,只需将其设置为网格(或其他面板)的背景:
以下是它最终的样子:
If you want to generate the brush dynamically, here's an equivalent function based on the above XAML:
You don't really have to "draw" anything with WPF. If you want to draw lines, use the appropriate geometries to draw them.
In your case it could be simple really. You're just drawing a grid so you could just create a
DrawingBrush
to draw a single grid square and tile it to fill in the rest. To draw your tile, you could think of it as drawing X's. So to have a20x10
tile (which corresponds tostepX
andstepY
):(p.s., the slope
slop
is redundant since you already have the horizontal and vertical step sizes)That takes care of drawing the lines. Now to be able to draw them offset in your grid from the edges, you need to have another brush where you draw a rectangle with the desired dimensions, filled with your tiles. So to have a starting position of
(30, 45)
(corresponding tostartX
andstartY
) with thewidth
andheight
,130x120
:Then finally to use it, just set it as the background of your grid (or other panel):
Here's how it ends up looking like:
If you want to generate the brush dynamically, here's an equivalent function based on the above XAML: