0

我有一个方法 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();            
        }

什么都没发生。

4

1 回答 1

2

尝试这个:

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);
}
于 2013-06-09T20:01:39.167 回答