简体   繁体   中英

Drawing a straight line in visual studio C# by the user along with the line moving along with the mouse?

the user should be able to draw a straight line on a panel similar to drawing a straight line in paint .

the user clicks on the panel and when he moves the mouse the line should also move along with the mouse (ie similar to drawing a staright line in paint) and when the user releases the mouse the line should have been drawn from the original point of click to this release point .

ie not a free hand line.

is there any animation for this ?

How about this? :

public class LinePanel : Panel
{
    public LinePanel()
    {
        this.MouseDown += (src, e) => { LineStartPos = LineEndPos = e.Location; Capture = true; Invalidate(); };
        this.MouseMove += (src, e) => { if (Capture) { LineEndPos = e.Location; Invalidate(); } };
        this.MouseUp += (src, e) => { if (Capture) { LineEndPos = e.Location; } Capture = false; Invalidate(); };
    }

    private Point LineStartPos, LineEndPos;

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (LineStartPos != LineEndPos)
            e.Graphics.DrawLine(new Pen(Color.Black, 2), LineStartPos, LineEndPos);
    }
}

To test you can just add a new LinePanel() to the Controls collection of your form, and set location/size or anchor / dock paramaters to size it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM