简体   繁体   English

位图不会出现在表单中

[英]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. 您可以修改代码以将位图绘制到窗体上,但是正如nvoigt在注释中建议的那样,更好的解决方案是使用PictureBox控件。 When you create your bitmap, you can assign that bitmap to the picture box's Image property: 创建位图时,可以将该位图分配给图片框的Image属性:

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. 如果绝对必须在窗体本身上绘制,则可以覆盖窗体的OnPaint方法,并使用图形对象的DrawImage()方法在此处渲染位图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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