开发者

How to draw a selectable line?

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();
    }


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜