简体   繁体   中英

bitmap won't appear in form

I am trying to make a bitmap appear in my form, but it won't work.

my code:

private void button2_Click(object sender, EventArgs e)
{
    Graphics g = this.CreateGraphics();
    Pen pen = new Pen(Color.Black);

    Bitmap bitmap = new Bitmap(1000, 1000);
    Graphics gfx = Graphics.FromImage(bitmap);
    gfx.Clear(Color.Red);

    for (int i = 0; i < 5; i++)
    {
        gfx.DrawRectangle(pen, i + 50, 50, 50, 50);
    }
}

All your code is doing is drawing to a bitmap, in memory. You don't have any code to actually display that bitmap anywhere.

You could modify the code to paint the bitmap onto the form, but as nvoigt suggested in comments, a better solution would be to use a PictureBox control. When you create your bitmap, you can assign that bitmap to the picture box's Image property:

Bitmap bitmap = new Bitmap(1000, 1000);
// render bitmap

pictureBox1.Image = bitmap;

If you absolutely must draw on the form itself, you can override the form's OnPaint method, and use the graphics object's DrawImage() method to render your bitmap there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM