将PaintEventArgs传递给我的函数会导致错误

时间:2014-06-02 05:21:48

标签: c# winforms

我试图创建一个绘制地图的函数。我的功能是这样的:

public void DrawMap(PaintEventArgs e)
{
    List<Point> lstPointLeft = new List<Point>();

    foreach (var t in lstSensorLeft)
    {
        Point objPoint = new Point(t.XLocation, t.YLocation);
        lstPointLeft.Add(objPoint);
        Rectangle rectSens = new Rectangle(t.XLocation, t.YLocation, 3, 3);
        e.Graphics.FillRectangle(whiteBrush, rectSens);
        if (t.StationId != null)
        {
            Rectangle rectEhsansq = new Rectangle(t.XLocation - 6, t.YLocation - 6, 12, 12);
            e.Graphics.FillRectangle(blueBrush, rectEhsansq);

        }
    }

    List<Point> lstPointRight = new List<Point>();

    foreach (var t in lstSensorRight)
    {
        Point objPoint = new Point(t.XLocation + 30, t.YLocation + 30);
        lstPointRight.Add(objPoint);
        Rectangle rectSens = new Rectangle(t.XLocation + 30, t.YLocation + 30, 3, 3);
        e.Graphics.FillRectangle(whiteBrush, rectSens);
        if (t.StationId != null)
        {
            Rectangle rectPosition = new Rectangle(t.XLocation + 24, t.YLocation + 24, 12, 12);
            e.Graphics.FillRectangle(blueBrush, rectPosition);

            Rectangle rectTrainState = new Rectangle(t.XLocation + 27, t.YLocation + 27, 7, 7);
            e.Graphics.FillRectangle(RedBrush, rectTrainState);

        }
    }


    e.Graphics.DrawLines(pLine, lstPointLeft.ToArray());
    e.Graphics.DrawLines(pLine, lstPointRight.ToArray());
    //ShowOnlineTrain(e);
    //Thread newThread = new Thread(() => ShowOnlineTrain(e));
    //newThread.Start();
}

此功能绘制我的地图,我的表单中有PictureBox来显示我的地图。这个函数DrawMap绘制了一张没有任何东西的铁路地图。我的问题是如何在page_Load中调用此函数?我尝试过这样的事情:

我创建了一个全球性的painteventarg:

private PaintEventArgs a;

form_load我正在这样做:

private void frmMain_Load(object sender, EventArgs e)
{

    DrawMap(a);

}

在这一行:

e.Graphics.FillRectangle(whiteBrush, rectSens);

我收到以下错误:

{System.NullReferenceException: Object reference not set to an instance of an object.
   at PresentationLayer.PreLayer.frmMain.DrawMap(PaintEventArgs e) 

1 个答案:

答案 0 :(得分:0)

我觉得你的DrawMap方法应该将Graphics对象作为参数而不是PaintEventArgs

public void DrawMap(Graphics g)
{
    ...
    g.FillRectangle(whiteBrush, rectSens);
    ...
}

然后你可以传递你想要绘制地图的东西的图形对象。例如Get the graphics object of an image

private void frmMain_Load(object sender, EventArgs e)
{
    Image img = new Bitmap(100, 100);
    Graphics g = Graphics.FromImage(img);
    DrawMap(g);
    myPictureBox.Image = img;
}

这可以在任何方法中完成,而不仅仅是在Load事件中,但请注意,您可能需要在绘制控件后刷新控件以查看任何更改。

myPictureBox.Refresh();

或者,你可以get the graphics object from a control

Graphics g = myPictureBox.CreateGraphics()
DrawMap(g);

但是,如果你使用它,那么你可能会遇到控件重新绘制本身和清除地图的问题(例如,当控件或窗口被调整大小或被另一个窗口隐藏时)。在这种情况下,最好将绘图放在控件的Paint事件中。