如何在表单启动时将图形绘制到表单

时间:2013-06-25 15:25:17

标签: c# .net graphics

我试图在表单启动时在表单上绘制图形。我已经尝试将图形组件放在表单构造函数中,但我似乎无法使它工作。这就是我到目前为止所做的。

public partial class Form3 : Form
{
    public Form3()
    {
        System.Drawing.Graphics graphics = this.CreateGraphics();
        System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);
        graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
        graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
    }

}

任何和所有帮助都会很棒,

谢谢你们

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用位图,例如

Bitmap b = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(b);
... // Draw
this.BackgroundImage = b;

否则,您将需要处理Paint事件,每次表单无效时,您都可以直接绘制到图形上下文。 e.g。

this.Paint += Form1_Paint;

...

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);
    g.DrawEllipse(System.Drawing.Pens.Black, rectangle);
    g.DrawRectangle(System.Drawing.Pens.Red, rectangle);
}

答案 1 :(得分:1)

private void Form1_Paint(object sender, PaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);
            e.Graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
            e.Graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
        }