Jon Martin
Jon Martin

Reputation: 3392

Windows Forms graphics not being drawn

I have some code that looks pretty simple and should draw an ellipse, but it doesn't seem to appear. Here is my code:

public partial class ThreeBodySim : Form
{

    public ThreeBodySim()
    {
        InitializeComponent();
        this.DoubleBuffered = true;
        Graphics graphics = displayPanel.CreateGraphics(); // Separate panel to display graphics
        Rectangle bbox1 = new Rectangle(30, 40, 50, 50);
        graphics.DrawEllipse(new Pen(Color.AliceBlue), bbox1);
    }
}

Am I missing something important?

Upvotes: 4

Views: 5438

Answers (2)

Matt
Matt

Reputation: 27016

The PictureBox works fine, but if you want to draw directly on the form, you can use the form's own OnPaint event, like:

protected override void OnPaint(PaintEventArgs pe)
{
    base.OnPaint(pe);
    for (int x = 0; x < 100; x++)
    {
            for (int y = 0; y < 100; y++)
            {
                pe.Graphics.FillEllipse(Brushes.Tomato, new Rectangle(x, y, 2, 2));
            }
    }
}

Upvotes: 0

John Alexiou
John Alexiou

Reputation: 29264

Use the Paint() event to draw on your form. I recommend using a PictureBox on the form as it will not have as much flicker.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

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

        this.DoubleBuffered=true;
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        Rectangle bbox1=new Rectangle(30, 40, 50, 50);
        e.Graphics.DrawEllipse(new Pen(Color.Purple), bbox1);
    }

    private void pictureBox1_Resize(object sender, EventArgs e)
    {
        pictureBox1.Invalidate();
    }
}

Form

Upvotes: 5

Related Questions