How to draw a selectable line?

不打扰是莪最后的温柔 提交于 2019-12-30 10:53:08

问题


I want to create an application which the user is able to manipulate the line he draw. Something like Deleting the line or Selecting it. How should I do that?

Thanks in advance


I managed to do it using a hard coded rectangle. But I don't still have an idea how to do it using the drawLine() Can I use drawPath to do the hit test?

Here is the code:

private bool selectGraph = false;
private Rectangle myrec = new Rectangle(50, 50, 100, 100);
private Graphics g;

private void panel1_Paint(object sender, PaintEventArgs e)
    {
        SolidBrush sb = new SolidBrush(Color.Blue);
        Pen p = new Pen(Color.Blue, 5);

        e.Graphics.DrawRectangle(p, myrec);
        e.Graphics.FillRectangle(sb, myrec);
    }

    private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        Point mPT = new Point(e.X, e.Y);

        if (e.Button == MouseButtons.Left)
        {
            if (myrec.Contains(mPT))
            {
                selectGraph = true;
                button1.Enabled = true;
            }
            else
            {
                selectGraph = false;
                button1.Enabled = false;
            }
        }
        Invalidate();
    }

回答1:


Well you could start with something like a simple Line class:

public class Line
{
    public Point Start { get; set; }
    public Point End { get; set; }
}

Then you could have your form:

private Line Line = new Line();

protected override void OnPaint(PaintEventArgs e)
{
    e.Graphics.DrawLine(Pens.Red, this.Line.Start, this.Line.End);
}

protected override void OnMouseMove(MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        this.Line.Start = e.Location;
        this.Refresh();
    }
    else if (e.Button == MouseButtons.Right)
    {
        this.Line.End = e.Location;
        this.Refresh();
    }
}

So basically then they could delete the this.Line maybe on "MiddleButton" click or something. This should be enough to get you started.

I've created a sample that shows how this can be done. Set some break points and see how things are done.




回答2:


There is no easy one line solution for this. You would have to program this yourself.

You have to keep track of every object you have drawn. In the onmousedown event you have to find out if the mouse has clicked on or near an object you want to move/delete by comparing coordinates. Then you need to draw some visual guide that the line is 'selected'. Deleting is now quite easy by removing the object from the collection.

For drag and drop you have to do something similar by changing the coordinates of the object according to the mouse move.



来源:https://stackoverflow.com/questions/3597069/how-to-draw-a-selectable-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!