PictureBox不显示在方法中绘制的网格
本文关键字:绘制 网格 方法 显示 PictureBox | 更新日期: 2023-09-27 18:17:30
我有一个方法CreateGrid():
public void CreateMyGrid()
{
g = pictureBox1.CreateGraphics();
for (int c = 0; c < columns; c++)
{
for (int r = 0; r < rows; r++)
{
g.DrawRectangle(pen1, cellSize * c, cellSize * r, cellSize, cellSize);
Cell newCell = new Cell(rows * columns, new Vector(c, r));
newCell.rectangle = new Rectangle(cellSize * c,
cellSize * r,
cellSize,
cellSize);
gridList.Add(newCell);
}
}
foreach (Cell cell in gridList)
{
if (cell.positionCR.X == start.X && cell.positionCR.Y == start.Y)
{
g.DrawImage(potato, cell.rectangle.X + 1, cell.rectangle.Y + 1);
}
if (cell.positionCR.X == goal.X && cell.positionCR.Y == goal.Y)
{
g.DrawImage(cake, cell.rectangle.X + 1, cell.rectangle.Y + 1);
}
}
}
如果我通过Button_Click调用相同的代码,则绘制网格。但是如果我在构造函数中像这样调用方法:
public Form1()
{
InitializeComponent();
CreateMyGrid();
}
什么也不会发生。
试试这个:
public void CreateMyGrid(Graphics g)
{
for (int c = 0; c < columns; c++)
{
for (int r = 0; r < rows; r++)
{
g.DrawRectangle(pen1, cellSize * c, cellSize * r, cellSize, cellSize);
Cell newCell = new Cell(rows * columns, new Vector(c, r));
newCell.rectangle = new Rectangle(cellSize * c,
cellSize * r,
cellSize,
cellSize);
gridList.Add(newCell);
}
}
foreach (Cell cell in gridList)
{
if (cell.positionCR.X == start.X && cell.positionCR.Y == start.Y)
{
g.DrawImage(potato, cell.rectangle.X + 1, cell.rectangle.Y + 1);
}
if (cell.positionCR.X == goal.X && cell.positionCR.Y == goal.Y)
{
g.DrawImage(cake, cell.rectangle.X + 1, cell.rectangle.Y + 1);
}
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e){
CreateMyGrid(e.Graphics);
}