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

时间:2015-11-06 08:40:36

标签: c# visual-studio paint paintevent

我一直在为一个项目工作,我需要在屏幕多边形上显示(在Panel中绘制),但我一直在这里阅读我应该使用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方法做到这一点吗? (它被称为方法或事件?我真的迷失在这里)。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你指的是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);
    }
}