Draw, move, and delete line segments in C#

[delete line segments]

This example shows how to make a drawing program that lets you draw, move, and delete line segments. It’s based on the example
Draw and move line segments in C#. See that example for information about how the program lets you draw and move line segments.

This example adds the ability to delete a line segment by dragging it into the trash can. To do that, the program must draw the trash can and detect when you move a segment onto it.

At design time, I added the trash can image (a PNG file with a transparent background) to the program’s resources. (Open the Project menu and select Properties. On the Resources tab, open the Add Resource dropdown and select Add Existing File.) When the program starts, the following code gets the trash can’s dimensions.

// Calculate the trash can dimensions.
private int TrashWidth, TrashHeight;
private void Form1_Load(object sender, EventArgs e)
{
    const float TrashScale = 0.25f;
    TrashWidth = (int)(TrashScale *
        Properties.Resources.trash_empty.Width);
    TrashHeight = (int)(TrashScale *
        Properties.Resources.trash_empty.Height);
}

This code defines the TrashWidth and TrashHeight variables. The form’s Load event handler sets those values to the trash can image’s dimensions multiplied by a scale factor.

The PictureBox object’s Paint event handler draws the current line segments as in the previous example. It then uses the following code to draw the trash can in the upper left corner.

// Draw the trash can.
Rectangle trash_rect = new Rectangle(0, 0,
    TrashWidth, TrashHeight);
e.Graphics.DrawImage(
    Properties.Resources.trash_empty,
    trash_rect);

This code simply creates a rectangle in the upper left corner of the PictureBox that has the desired trash can dimensions. It then calls e.DrawImage to draw the trash can there.

The last and most interesting piece of new code deletes a segment when the user drops it in the trash can.

When you drag a segment to a new location and then release the mouse, the following event handler executes. The new code is shown in blue.

// Stop moving the segment.
private void picCanvas_MouseUp_MovingSegment(
    object sender, MouseEventArgs e)
{
    // Reset the event handlers.
    picCanvas.MouseMove += picCanvas_MouseMove_NotDown;
    picCanvas.MouseMove -= picCanvas_MouseMove_MovingSegment;
    picCanvas.MouseUp -= picCanvas_MouseUp_MovingSegment;

    // See if the mouse is over the trash can.
    if ((e.X >= 0) && (e.X < TrashWidth) &&
        (e.Y >= 0) && (e.Y < TrashHeight))
    {
        if (MessageBox.Show("Delete this segment?",
            "Delete Segment?", MessageBoxButtons.YesNo)
                == DialogResult.Yes)
        {
            // Delete the segment.
            Pt1.RemoveAt(MovingSegment);
            Pt2.RemoveAt(MovingSegment);
        }
    }

    // Redraw.
    picCanvas.Refresh();
}

This code resets the PictureBox event handlers for the situation when the user isn’t dragging anything. The new code then determines whether the mouse is over the trash can. If it is, the program asks the user whether it should delete the line segment. If the user clicks Yes, the program removes the points that define the segment that was dragged.

The method finishes by refreshing the PictureBox to make it redraw the remaining line segments.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in drawing, graphics and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

15 Responses to Draw, move, and delete line segments in C#

  1. Pooja Shahane says:

    I want to draw another same line in different color on the same picturebox. but when I try same code with different list of points it will replace first blue lines with red lines.Can you tell me how to draw two different lines on the same picturebox which will be move,stretch and delete

    • RodStephens says:

      If you use the same points, the new line will overdraw the old one. It sounds like maybe you’re using the same points instead of the new ones.

      • Pooja Shahane says:

        I created new list with different points and also I changed all points still it is overdraw the old one…Can you please send source code of drawing two lines??

        • RodStephens says:

          This example uses two lists named Pt1 and Pt2 to hold the end points of the segments. Those are the lines it draws in the Paint event handler.

          You need to either:

          1. Add your new lines to those lists. Then you get new segments in the same color.

          2. Make new similar lists and put the new points in them. Then you can make the Paint event handler draw them in a new color after it draws the first set.

          Do one or the other, not both.

          This example isn’t really intended to be a full-featured editor where you can draw lines with different colors, widths, etc. It’s more to show how you can move segments.

  2. kavin says:

    hi,i need to measure length of the line which are dragged and similarly i need to draw and measure reactangle,circle,arc,ellipse,polygon.can you help me?..
    —thank you in advance–

    • RodStephens says:

      You can calculate the measurements by just finding the distance between the two points. You can multiply by a scale factor if you’re working on a map or some other drawing with a scale.

      For other shapes such as rectangles and ellipses, just change the way the program draws them. For example, instead of calling DrawLine, call DrawRectangle.

      This example may help:

      Let the user draw polygons in C#

      Unfortunately I don’t have time to write the rest of it for you, unless you want to hire me to do it. If you want that, email me.

  3. Taghi Tanasa says:

    Hi , your example is very good.
    Thank you.

  4. Givanildo says:

    Hello Sir Rod Stephens.
    You can provide the draw, move, and delete line segments in C # project in vb.net.
    Thank you for your attention.
    Givanildo

  5. Ravishankar says:

    Hello sir, thanks a lot for this example. It help me a lot,
    but I have one doubt.

    I need to move multiple lines at a time using ISelectable interface. But I am unable to do.can u help me boss

    • RodStephens says:

      First you would need to provide some sort of multi-select. You could use click-and-drag to select segments that intersect the area that you select. You could also use Shift+Click or Ctrl+Click to add and remove items from the selection.

      You would need to change the program so it draws selected objects differently so the user can see which are selected. And it would need to be able to keep selected items even when the mouse is not pressed. Right now the program doesn’t retain the selection when the mouse is up.

      Then when the user clicks and drags starting on a selected item, you would move the whole group.

      All of this is doable but fairly complicated. (I don’t know about the ISelectable interface.)

  6. waqas says:

    its not deleting when i click the trash icon

  7. Pingback: Make a WPF line editor C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *