0
public void GridCreate()
    {
        Graphics g = pictureBox1.CreateGraphics();
        SolidBrush brushBlack = new SolidBrush(Color.Black);
        Rectangle[,] block = new Rectangle[16, 16];

        for (int i = 0; i <= block.GetLength(0) - 1; i++)
        {
            for (int n = 0; n <= block.GetLength(0) - 1; n++)
            {
                block[n, i] = new Rectangle(i * blockSize, n * blockSize, 20, 20);
                g.FillRectangle(brushBlack, block[n, i]);
            }
        }
        data.block = block;
    } 
private void Form1_Shown(object sender, EventArgs e)
        {
            GridCreate();
        }

WindowsFormsでPictureBoxを使ってグリッドを作ろうとしているのですが、関連するコードがうまく動きdata.block = block;ませg.FillRectangle(brushBlack, block[n, i]);ん。Form1_Shownこれは次の理由から、問題はイベントにあると思います。

private void Form1_Click(object sender, EventArgs e)
    {
        GridCreate();
    }

完全に正常に実行されます。

Overrideprotected override void OnShown(EventArgs e)は と同じ結果になりForm1_Shownます。

4

1 に答える 1

4

問題はCreateGraphics()、PictureBox が更新されると消去される 一時的なサーフェスです。

一度グリッドを作成してから、Paint() イベントでデータを描画します。

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        GridCreate();
        pictureBox1.Paint += pictureBox1_Paint;
    }

    private void GridCreate()
    {
        Rectangle[,] block = new Rectangle[16, 16];
        for (int i = 0; i < block.GetLength(1); i++) // this is the 2nd dimension, so GetLength(1)
        {
            for (int n = 0; n < block.GetLength(0); n++) // this is the 1st dimension, so GetLength(0)
            {
                block[n, i] = new Rectangle(i * blockSize, n * blockSize, 20, 20);
            }
        }
        data.block = block;
    }

    void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics; // use the SUPPLIED graphics, NOT CreateGraphis()!
        for (int i = 0; i < data.block.GetLength(1); i++) // this is the 2nd dimension, so GetLength(1)
        {
            for (int n = 0; n < data.block.GetLength(0); n++) // this is the 1st dimension, so GetLength(0)
            {
                g.FillRectangle(Brushes.Black, data.block[n, i]);
            }
        }
    }
于 2015-01-25T18:46:47.033 に答える