如何在图片框中绘制直线到鼠标坐标? [英] How to draw straight line to the mouse coordinates in picturebox?

查看:94
本文介绍了如何在图片框中绘制直线到鼠标坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户按下左键并移动鼠标时,它应显示从前一点到当前鼠标移动位置的直线(非永久线)。最后,当用户释放鼠标时,会出现一条真正的直线。请帮帮我..我是怎么做的?

 private void pictureBox1_MouseDown(object sender,MouseEventArgs e)
{
if(e.Button = = MouseButtons.Left)
{
points.Add(e.Location);
pictureBox1.Invalidate();
}
}

private void pictureBox1_Paint(object sender,PaintEventArgs e)
{
if(points.Count> 1)
e.Graphics.DrawLines(Pens.Black,points.ToArray());
}

解决方案

这与你所拥有的不是很大的改变,

在MouseDown中,清除 points 集合,并添加起点。使PictureBox无效。在MouseDown事件处理程序中添加一个类级别bool,其中显示Collecting points并将其设置为 true

然后处理MouseMove事件,并且如果你正在收集点,在那里添加每个新点 - 再次失效。

在MouseUp处理程序中,将收集点设置为false。



这不会使它们成为永久性的 - 您正在绘制屏幕,​​而不是PictureBox中的图像 - 但如果您需要这样做,那么使用Graphics.FromImage方法获取上下文,并使用DrawLines方法相反(当你完成它时不要忘记处理上下文) - 但是当用户对这些行感到满意时你可能只想做一次。



请注意,从鼠标事件中获取的位置将以表单形式表示,因此如果图片框未填充,则线条将偏移很多,您可能需要移动它们。

When user press the left button and move the mouse it should appears a straight line(not permanent line) from previous point to the current mouse moving position. Finally a real straight line will appear when the user releases the left mouse. please help me ..how do i do it?

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        points.Add(e.Location);
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (points.Count > 1)
       e.Graphics.DrawLines(Pens.Black, points.ToArray());
}

解决方案

It's not a big change from what you have,
In the MouseDown, clear the points collection, and add the start point. Invalidate the PictureBox. Add a class level bool which says "Collecting points" and set it to true in the MouseDown event handler.
Then handle the MouseMove event, and if you are collecting points add each new point in there - invalidate again.
In the MouseUp handler, set "Collecting Points" to false.

This won't make them permanent - you are drawing on the screen, not the image in the PictureBox - but if you need to do that, then use the Graphics.FromImage method to get a context, and use the DrawLines method on that instead (don't forget to Dispose the Context when you have finished with it) - but you probably want to do that just once when the user is happy with the lines.

Do note that the location you get from the mouse events will be in terms of the form, so if the picture box doesn't fill it, then the lines will be offset quite a bit and you may need to move them.


这篇关于如何在图片框中绘制直线到鼠标坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆