【问题标题】:C# - Drawing in a panel with "Paint"C# - 使用“Paint”在面板中绘图
【发布时间】:2015-11-06 08:40:35
【问题描述】:

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

谢谢!

【问题讨论】:

  • 你好@Tchangla,欢迎来到 StackOverflow!在 C# 中,可以通过 event handler 订阅事件。事件处理程序看起来就像一个方法,它基本上是。不同之处在于,每次它订阅的事件触发时都会调用此方法。这确实需要它具有特定的签名(简单来说:参数需要匹配事件的类型。)

标签: c# visual-studio paint paintevent


【解决方案1】:

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

【讨论】:

  • 我应该如何调用这个事件?我的意思是,我正在尝试使用“playerView_Paint();”这不起作用(我不知道在 "()" 里面写什么)。
  • 您不必这样做 :) windows.forms 控件会在需要时自行触发绘制事件。您所要做的就是使用事件处理程序订阅事件。 (这就是我的示例代码所做的)
  • 你通过调用panel.Invalidate();@timothy来触发事件:不,他必须在他的绘图数据发生变化时调用/触发它。 Windows 将不会选择它。当然,只要他没有可变的绘图数据,这是没有实际意义的,但我敢打赌这会改变。另外:DisposePen 或使用Pens.White!跨度>
  • @TaW 是的,这是一种强制 windows.forms 元素触发事件的方法。
  • @TaW 关于处理笔的好点。我更新了示例
猜你喜欢
  • 2011-07-27
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
相关资源
最近更新 更多