0

I've been learning how to draw lines in winforms apps, and I'd like to be able to select something (rectangle, for example) that has already been drawn by left clicking it, and then be able to move it around to another location by dragging it with the mouse.

How can this be done? I don't see any methods for this so I think I will need to figure out if there is anything where I left-click on the form, and if there is, then somehow figure out the dimensions of it and redraw it appropriately. Is this correct? And how would I know where the reactangle starts, where it ends, how heigh it is, what color(s) it has, and what if it's overlapping another line, rectangle or another shape?

I've not been able to find much on the System.Drawing namespace for things like this, and what I have found so far is just basic "How to draw lines" type stuff.

jay_t55
  • 11,362
  • 28
  • 103
  • 174

1 Answers1

2

Your drawing is a bitmap, not a vectorial image. Basically, it's just lots of pixels. Once your rectangle is drawn, it's just some pixels, but the rectangle itself (with coordinates and size) doesn't exist anymore. What you can do is saving data for every shape (in a List for example). Then, when you click on your image to select something, you test every object in your list in reverse order until the mouse coordinates are within your shape. Then, if, for example, you want to delete the shape, you remove the shape from your list, then you clear your image and redraw every shape in your list.

krimog
  • 1,257
  • 11
  • 25
  • Thank you @krimog. I see one potential problem with this (or maybe I am just wrong): If there is a shape partially overlapping the shape i clicked on, and i get the coorinates of the clicked shape and clear that shape, will the area of the overlapping shape also be cleared (because it was partially in the same location as the cleared shape)? – jay_t55 Aug 21 '14 at 08:44
  • 1
    No. You don't clear that shape. You redraw the whole image (thanks to your list) except the shape you deleted. So any overlapping shape will still be there, without any cleared part. – krimog Aug 21 '14 at 09:08
  • 1
    Note: In order to make your drawing persist, say minimizing the window, you must draw all your shapes in the Paint event __anyway__! You also may want to think about the best way to select: There is a Rectanlge.Contains(Point) method and if you go through your list you could find all fitting items and offer them to pick from.. – TaW Aug 21 '14 at 10:19
  • @TaW : That is if you draw on a Control (then, you're absolutely right). But if you draw on a System.Drawing.Bitmap object, this is persistant. And I didn't know the Contains(Point) method. Quite useful ! – krimog Aug 21 '14 at 12:06
  • Yes, that's right. OTOH you can't really move the shapes around with the mouse when they have been drawn into the Bitmap. One can combine a PictureBox with an Image and still draw onto it.. – TaW Aug 21 '14 at 12:18