简体   繁体   English

C# - 在带有“Paint”的面板中绘图

[英]C# - Drawing in a panel with "Paint"

I've been working on a project for class where I need to display on screen polygons (drawed in a Panel), but I've been reading arround here that I should work with Paint event, tho I can't make it work (started learning C# a little ago).我一直在为班级设计一个项目,我需要在屏幕上显示多边形(在面板中绘制),但我一直在这里阅读我应该使用 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);
}

I was doing something like this to draw it on screen, it would be possible to do this with a Paint method?我正在做这样的事情来在屏幕上绘制它,可以用 Paint 方法来做到这一点吗? (it is called method, or event? I'm really lost here). (它被称为方法,或事件?我真的在这里迷路了)。

Thanks!谢谢!

I think you are referring to the Control.Paint event from windows forms .我认为您指的是Windows 窗体中Control.Paint事件

Basically, you would attach a listener to the Paint event of a windows forms element, like this :基本上,您可以将侦听器附加到 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM