C#通过拖动绘制线条 [英] c# draw lines with dragging

查看:108
本文介绍了C#通过拖动绘制线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像Windows Paint那样绘制一条线,单击以固定第一个点,然后用鼠标移动第二个点(和该线),再单击以固定该线.

How to draw a line like the windows Paint does, single click for a fixed first point, and the second point (and the line) moves with mouse, another click fixes the line.

int x = 0, y = 0;
protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    // Create the graphics object
    Graphics g = CreateGraphics();
    // Create the pen that will draw the line
    Pen p = new Pen(Color.Navy);
    // Create the pen that will erase the line
    Pen erase = new Pen(Color.White);
    g.DrawLine(erase, 0, 0, x, y);
    // Save the mouse coordinates
    x = e.X; y = e.Y;
    g.DrawLine(p, 0, 0, x, y);
}

单击事件部分很好,但是使用上述方法,擦除线实际上是白线,与其他背景图像和先前绘制的蓝线重叠.

The clicking event part is fine, but with this method above, the erase line is actually white lines, which overlaps on other background image and previously plotted blue lines.

是否有更容易管理的方法来实现?谢谢

Is there a more manageable way to make it happen? Thanks

推荐答案

应在 OnPaint 事件中实现窗体工作区上的任何图形,以免产生任何奇怪的影响.考虑以下代码片段:

Any drawing on the form client area should be implemented in the OnPaint event to avoid any strange effects. Consider the following code fragment:

Point Latest { get; set; }

List<Point> _points = new List<Point>(); 

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    // Save the mouse coordinates
    Latest = new Point(e.X, e.Y);

    // Force to invalidate the form client area and immediately redraw itself. 
    Refresh();
}

protected override void OnPaint(PaintEventArgs e)
{
    var g = e.Graphics;
    base.OnPaint(e);

    if (_points.Count > 0)
    {
        var pen = new Pen(Color.Navy);
        var pt = _points[0];
        for(var i=1; _points.Count > i; i++)
        {
            var next = _points[i];
            g.DrawLine(pen, pt, next);
            pt = next;
        }

        g.DrawLine(pen, pt, Latest);
    }
}

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    Latest = new Point(e.X, e.Y);
    _points.Add(Latest);
    Refresh();
}

这篇关于C#通过拖动绘制线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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