从鼠标移动事件调用绘制事件

时间:2013-04-05 20:53:24

标签: c# winforms paint

当鼠标在panel2上移动时,我需要绘制线条。到目前为止,我已经完成了以下

public Form1()
{           
    InitializeComponent();            

}

private void panel2_Paint(object sender, PaintEventArgs e)
{
    if (isDragging)
    {
        letsPaint(sender, e);
    }
}

private void panel2_MouseMove(object sender, MouseEventArgs e)
{
    if (isDragging) 
    {
        mouseMoveX = e.X;
        mouseMoveY = e.Y;                               
        this.Paint += new PaintEventHandler(panel2_Paint);
    }
}

private void letsPaint(object sender, PaintEventArgs e) 
{             
    Pen blackpen = new Pen(Color.Black, 3);
    Graphics g = e.Graphics;
    g.DrawLine(blackpen, mouseClickedX, mouseClickedY, mouseMoveX, mouseMoveY);
    g.Dispose(); 
}

但是当我移动鼠标时没有任何反应。我想我在这里做错了PaintEventHandler()。请告诉我如何做到这一点,以及是否有更好的方法。

另外我认为我的方法会在表单上绘制,但我需要在panel2上画线。怎么做?提前致谢。

1 个答案:

答案 0 :(得分:4)

您无效:

public Form1()
{           
  InitializeComponent();            
  panel2.Paint += new letsPaint;
}

private void panel2_MouseMove(object sender, MouseEventArgs e)
{
  if (isDragging) {
    mouseMoveX = e.X;
    mouseMoveY = e.Y;                               
    panel2.Invalidate();
  }
}

并且你没有处理图形对象(你没有创建它),但是你做了笔:

private void letsPaint(object sender, PaintEventArgs e) {             
  using (Pen blackpen = new Pen(Color.Black, 3)) {
    e.Graphics.DrawLine(blackpen, 
                        mouseClickedX, mouseClickedY, mouseMoveX, mouseMoveY);
  }
}

这是一个使用位图的快速小方法:

Bitmap bmp;
Point lastPoint;

public Form1() {
  InitializeComponent();
  bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height, 
                   System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

  panel1.MouseDown += panel1_MouseDown;
  panel1.MouseMove += panel1_MouseMove;
  panel1.Paint += panel1_Paint;
}

void panel1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.DrawImage(bmp, Point.Empty);
}

void panel1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    using (Graphics g = Graphics.FromImage(bmp)) {
      g.DrawLine(Pens.Black, lastPoint, e.Location);
    }
    lastPoint = e.Location;
    panel1.Invalidate();
  }
}

void panel1_MouseDown(object sender, MouseEventArgs e) {
  lastPoint = e.Location;
}

这会闪烁,因此您需要使用双缓冲面板更换面板。像这样:

public class PanelEx : Panel {
  public PanelEx() {
    this.DoubleBuffered = true;
  }
}