簡體   English   中英

顯示不起作用

[英]Shown doesn't work

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();
        }

我正在嘗試使用PictureBox在WindowsForms中創建網格,但相關代碼無法正常工作data.block = block; 部分有效,但此g.FillRectangle(brushBlack, block[n, i]); 根本不起作用。 我認為問題出在Form1_Shown事件中,因為:

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

執行得很好。

protected override void OnShown(EventArgs e)給出的結果與Form1_Shown相同。

問題是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]);
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM