为什么我在表单上绘制的方法不起作用?( C# )



[已解决] 我试图在控制台和绘图中模拟"生活游戏",但我的形式是纯白色的。如何使我的方法可用?

我在VisualStudio 2019中第一次使用c#代码,只是为了与基于对象的语言相处。我尝试了基于事件的绘图(鼠标单击,按钮),一切都很好。

我的窗体类如下所示:

public partial class Board : Form
{
private int BOARDWIDTH;
private int BOARDHEIGHT;
private int cellSize;
private bool paint = false; //ADDED IN
private World world;
Graphics drawArea;
public Board(World world, int cellsize)
{
this.BOARDHEIGHT = world.getWorldHeight() * cellsize;
this.BOARDWIDTH = world.getWorldWidth() * cellsize;
InitializeComponent();
drawingArea.SetBounds(0, 0, this.BOARDWIDTH, this.BOARDHEIGHT);
drawArea = drawingArea.CreateGraphics();
this.cellSize = cellsize;
this.world = world;
}
public void updateBoard(World world)
{
this.world = world;
}
protected override void OnPaint(PaintEventArgs e) // ADDED IN (Basically previous DrawCell inside)
{
base.OnPaint(e);
if(paint)
{
Rectangle rect = new Rectangle(x*this.cellSize, y*this.cellSize, 
this.cellSize, this.cellSize);
if (this.world.getCellState(x, y))
{
rect.Height--;
rect.Width--;
using (Pen wPen = new Pen(Color.Black))
{
e.Graphics.DrawRectangle(wPen, rect);
}
}
else
{
using (SolidBrush bBrush = new SolidBrush(Color.Black))
{
e.Graphics.FillRectangle(bBrush, rect);
}
}
paint = false;
}
}
private void DrawCell(int x, int y) //CHANGED
{
this.x = x;
this.y = y;
paint = true;
}
public void DrawWorld(int refreshRate)
{
for(int i = 0; i < this.world.getWorldHeight(); i++)
{
for(int j = 0; j <this.world.getWorldWidth(); j++)
{
DrawCell(j, i);
}
}
}
}
}

我的主要看起来像这样:

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
World world = new World(20, 20);
world.createRandomWorld();
Board board = new Board(world, 10);
Application.Run(board);
board.DrawWorld(10);
}

我想得到一个黑/白方块的网格,白色的边框。现在我唯一得到的是我的代码没有崩溃

[编辑] 我添加了OnPaint并更改了我的DrawCell方法,我现在有一些东西(它绘制,yaaay),但我只得到一个单元格,而不是整个网格。此外,我的bool paint解决方案感觉像是一种解决方法,而不是执行此操作的正确方法。如果有的话,我很想看到"正确"的工作代码,因为我不 Web(微软页面)上的定义/示例没有告诉我如何让它按照我的方式工作^.^

与其尝试绘制"现在这个单元格",不如在调用OnPaint时"按需"绘制整个World

您可以通过在窗体上调用Invalidate()来导致重绘,例如,当World中的某些内容发生更改时。OnPaint也会被自动调用,例如,当您的表单首次显示时,或者在被另一个窗口隐藏后重新出现时。

好的好的,所以在了解我不能"按照我的方式"做(使用称为外部板类的方法在表单上绘图)之后,我做了一些研究并添加了一个计时器 + 设置OptimizedDoubleBuffertrue。感谢所有提供帮助的人,如果有人想看看我现有的 Board 类,它看起来像这样:https://pastebin.com/CP9XRN6r(不想用不必要的代码占用空间),希望你会有一个美好的一天,我的帖子有一天会帮助某人^.^

最新更新