使用g.FillEllipse()时,我一直收到Null异常;

时间:2013-10-13 18:22:32

标签: c# graphics gdi

我是初学者,所以请给我一点松懈。我试图在单击鼠标的位置的窗体窗口上绘制一个点。我一直在g.FillEllipse上调用Null Exception。我错过了什么或做错了什么?

namespace ConvexHullScan
{

public partial class convexHullForm : Form
{
    Graphics g;
    //Brush blue = new SolidBrush(Color.Blue);
    Pen bluePen = new Pen(Color.Blue, 10);
    Pen redPen = new Pen(Color.Red);

    public convexHullForm()
    {
        InitializeComponent();
    }

    private void mainForm_Load(object sender, EventArgs e)
    {
        Graphics g = this.CreateGraphics();
    }     

    private void convexHullForm_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {

            int x, y;
            Brush blue = new SolidBrush(Color.Blue);
            x = e.X;
            y = e.Y;
            **g.FillEllipse(blue, x, y, 20, 20);**
        }                                             
    }
  }
}

2 个答案:

答案 0 :(得分:0)

Graphics g = this.CreateGraphics();替换为g = this.CreateGraphics();,否则您将定义一个仅存在于mainForm_Load函数范围内的新变量,而不是为更高级别定义的变量赋值-convexHullForm

的范围

答案 1 :(得分:0)

目前尚不清楚你的最终目标是什么,但用CreateGraphics()绘制的那些点只是暂时的。当表单重新绘制时,它们将被删除,例如当您最小化和恢复时,或者如果另一个窗口遮挡了您的窗口。要使它们“持久”,请使用表单的 Paint()事件中提供的e.Graphics

public partial class convexHullForm : Form
{

    private List<Point> Points = new List<Point>();

    public convexHullForm()
    {
        InitializeComponent();
        this.Paint += new PaintEventHandler(convexHullForm_Paint);
        this.MouseDown += new MouseEventHandler(convexHullForm_MouseDown);
    }

    private void convexHullForm_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            Points.Add(new Point(e.X, e.Y));
            this.Refresh();
        }                                             
    }

    void convexHullForm_Paint(object sender, PaintEventArgs e)
    {
        foreach (Point pt in Points)
        {
            e.Graphics.FillEllipse(Brushes.Blue, pt.X, pt.Y, 20, 20);
        }
    }

}