嗨,我想使用鼠标事件在winforms的图片框中画一条直线。我使用鼠标按下,鼠标移动和鼠标向上事件来绘制一条线。但是,当我移动鼠标时,还会绘制其他几条线。
如果有人能提供如何解决这个问题的指南,我真的很感激。
我还附上了我的代码片段供您参考。提前谢谢!
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mousepress = true;
x1 = e.Location.X;
y1= e.Location.Y;
if (counter>0)
{
this.Invalidate();
pictureBox1.Refresh();
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Graphics g = pictureBox1.CreateGraphics();
Pen newpen = new Pen(Color.Blue, 1);
if (mousepress)
{
g.DrawLine(newpen, x1, y1, e.Location.X, e.Location.Y);
x2 = e.Location.X;
y2 = e.Location.Y;
angle = GetAngle(x1, y1, x2, y2);
}
Invalidate();
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
mousepress = false;
double tempX=e.Location.X, tempY=e.Location.Y;
{
textBox_coordinates.Text = "Index: " + i + Environment.NewLine + "X: " + x2
+ Environment.NewLine + "Y: " + y2 + Environment.NewLine + "Angle: " + angle;
i++;
}
counter++;
}
答案 0 :(得分:0)
在MouseMove事件中,您还必须刷新PictureBox以清除您在上一次调用中绘制的行。并且永远不要忘记在分配之后处理非托管图形资源,除非你想要一个内存漏洞。
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
// vvv take care of automatic disposal
using (Graphics g = pictureBox1.CreateGraphics())
using (Pen newpen = new Pen(Color.Blue, 1))
{
if (mousepress)
{
pictureBox1.Refresh(); // <-- get rid of the previous lines
g.DrawLine(newpen, x1, y1, e.Location.X, e.Location.Y);
x2 = e.Location.X;
y2 = e.Location.Y;
angle = GetAngle(x1, y1, x2, y2);
}
// Invalidate(); // check if necessary!
}
}
编辑:获得所需内容的另一种方法是拦截绘制事件并在那里进行线条绘制(在继承绘制PictureBox之后)。我想大多数人会认为这是一个更干净的解决方案,因为这正是油漆事件的目的所在。但是如果你只是想快速完成你的狭隘任务,那么上面建议的解决方案就足够了。
答案 1 :(得分:0)
类似的东西...
public partial class Form1 : Form
{
bool mousepressed;
int x1=0, y1=0,x2=0,y2=0;
Pen newPen = new Pen(Color.Blue, 2);
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mousepressed = true;
x1 = e.X;
y1 = e.Y;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (mousepressed)
{
x2 = e.X;
y2 = e.Y;
pictureBox1.Refresh();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(newPen, x1, y1, x2, y2);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
mousepressed = false;
}
}