4

当鼠标移到 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 上画线。怎么做?提前致谢。

4

1 回答 1

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;
  }
}
于 2013-04-05T20:55:58.340 回答