C#..菜鸟问题,GDI+画直线,请进〉>>>

2024-12-28 11:34:07
推荐回答(4个)
回答1:

其实总共就两个点,一个鼠标按下,一个是鼠标离开 ;
int startX; //获取鼠标起始点的X坐标
int startY; //获取鼠标起始点的Y坐标
Graphics g; //定义Graphics对象实例

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
g = this.CreateGraphics();
Pen p = new Pen(Color.Red, 4);
g.DrawLine(p, startX, startY, e.X, e.Y);
}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
startX = e.X;
startY = e.Y;
}

回答2:

这么写就行了,不过建议你在PictureBox上画,不要直接画在窗体上

bool draw = false;
Point start = Point.Empty;
Point end = Point.Empty;
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (start != Point.Empty && end != Point.Empty)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.DrawLine(Pens.Black, start, end);
}
}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (start != Point.Empty)
{
if (!draw)
{
start = e.Location;
end = Point.Empty;
draw = true;
}
else
{
end = e.Location;
draw = false;
}
this.Invalidate();
}
else
{
start = e.Location;
draw = true;
}
}
else//右键清除画的线
{
start = end = Point.Empty;
this.Invalidate();
}
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (draw && start != Point.Empty)
{
end = e.Location;
this.Invalidate();
}
}

回答3:

楼上的已经给出答案了

回答4:

1L+1