2

我一直在为一个需要在屏幕上显示多边形(在面板中绘制)上显示的类项目工作,但我一直在这里阅读我应该使用 Paint 事件,但我不能让它工作(不久前开始学习 C#)。

private void drawView()
{
//"playerView" is the panel I'm working on
Graphics gr = playerView.CreateGraphics();
Pen pen = new Pen(Color.White, 1);


 //Left Wall 1
 Point lw1a = new Point(18, 7); 
 Point lw1b = new Point(99, 61); 
 Point lw1c = new Point(99, 259); 
 Point lw1d = new Point(18, 313);

 Point[] lw1 = { lw1a, lw1b, lw1c, lw1d };

 gr.DrawPolygon(pen, lw1);
}

我正在做这样的事情来在屏幕上绘制它,可以使用 Paint 方法来做到这一点吗?(它被称为方法或事件?我真的迷路了)。

谢谢!

4

1 回答 1

1

我认为您指的是Control.PaintWindows 窗体中的事件

基本上,您可以将侦听器附加到 windows 窗体元素的 Paint 事件,如下所示:

//this should happen only once! put it in another handler, attached to the load event of your form, or find a different solution
//as long as you make sure that playerView is instantiated before trying to attach the handler, 
//and that you only attach it once.
playerView.Paint += new System.Windows.Forms.PaintEventHandler(this.playerView_Paint);

private void playerView_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    // Create a local version of the graphics object for the playerView.
    Graphics g = e.Graphics;
    //you can now draw using g

    //Left Wall 1
    Point lw1a = new Point(18, 7); 
    Point lw1b = new Point(99, 61); 
    Point lw1c = new Point(99, 259); 
    Point lw1d = new Point(18, 313);

    Point[] lw1 = { lw1a, lw1b, lw1c, lw1d };

    //we need to dispose this pen when we're done with it.
    //a handy way to do that is with a "using" clause
    using(Pen pen = new Pen(Color.White, 1))
    {
        g.DrawPolygon(pen, lw1);
    }
}
于 2015-11-06T08:44:25.273 回答