C# - 使用 "Paint" 在面板中绘图

C# - Drawing in a panel with "Paint"

我一直在为 class 做一个项目,我需要在屏幕上显示多边形(在面板中绘制),但我一直在这里阅读我应该使用 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 方法来完成吗? (这叫方法,还是事件?我真是迷路了)

谢谢!

我想你指的是 Control.Paint event from windows forms

基本上,您可以将侦听器附加到 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);
    }
}