在Windows窗体中高效地绘制网格 [英] Efficiently draw a grid in Windows Forms
问题描述
我正在用C#写一篇康威的生命游戏的实现。这是我用来绘制网格的代码,它在我的panel_Paint事件中。 g是图形上下文。
for(int y = 0; y< numOfCells * cellSize; y + = cellSize)$ (p,x,0,x,y + b)的b $ b {
numOfCells * cellSize);
g.DrawLine(p,0,x,y + size * drawnGrid,x);
$ / code>
当我运行我的程序时,它直到它没有响应完成绘制网格,在numOfCells = 100& cellSize = 10。删除所有乘法使得它更快,但不是很多。
是否有更好/更有效的绘制网格的方法?
谢谢
问题在于你为每个Y绘制X行坐标。您可以先简化一个循环中的Y行,然后再循环另一个循环中的X行。
这里有一个简单的例子:
for(int y = 0; y {
g.DrawLine(p,0,y * cellSize,numOfCells * cellSize,y * cellSize);
for(int x = 0; x {
g.DrawLine(p,x * cellSize,0, x * cellSize,numOfCells * cellSize);
}
随着您的进步,您可以使用双缓冲来减少闪烁等。看看Control.SetStyle< br />
http:// msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx
I'm writing an implementation of Conway's Game of Life in C#. This is the code I'm using to draw the grid, it's in my panel_Paint event. g is the graphics context.
for (int y = 0; y < numOfCells * cellSize; y += cellSize)
{
for (int x = 0; x < numOfCells * cellSize; x += cellSize)
{
g.DrawLine(p, x, 0, x, y + numOfCells * cellSize);
g.DrawLine(p, 0, x, y + size * drawnGrid, x);
}
}
When I run my program, it is unresponsive until it finishes drawing the grid, which takes a few seconds at numOfCells = 100 & cellSize = 10. Removing all the multiplication makes it faster, but not by very much.
Is there a better/more efficient way to draw my grid?
Thanks
The problem is that you are drawing the X lines for every Y coordinate. You can simplify first by just rendering the Y lines in one loop and then the X lines in another loop.
Here is a quick example
for (int y = 0; y < numOfCells; ++y)
{
g.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);
}
for (int x = 0; x < numOfCells; ++x)
{
g.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);
}
As you progress, you can use double buffering to reduce any flashing etc. Take a look at Control.SetStyle < br/> http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx
这篇关于在Windows窗体中高效地绘制网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!