2014-06-09 109 views
1

我有一些看起来很简单的代码,应该绘制一个椭圆,但似乎并没有出现。这里是我的代码:Windows窗体图形没有绘制

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

我是否缺少重要的东西?

+1

使用Paint事件。您的CreateGraphics不能在构造函数中使用 - 表单不可见。 CreateGraphics也会忽略你的DoubleBuffer。 – LarsTech

回答

4

使用Paint()事件来绘制您的表单。我建议在表单上使用PictureBox,因为它不会有太多闪烁。

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