After drawing a Line, Rect, Ellipse, I want to click onto a shape and move it with mousemove event. How can I get which object is being chosen? Any help? Thanks in advance.
A:
You need to perform containment tests to see if the point you clicked is within any of the shapes. For example, for a point to be inside a circle, the following must evaluate to true:
Math.Pow(x - centerX, 2) + Math.Pow(y - centerY, 2) <= Math.Pow(radius, 2)
You should also implement some kind of Z-order (layering). After getting a list of all the shapes containing your point, choose the one at the top of the Z-order and that's your selected shape.
Andy West
2009-12-09 06:33:24
Thanks for your reply. So you mean that we just can get the shape with coordination, can't change it into object and get it. Right?
Thyphuong
2009-12-09 06:55:33
You will need to store and maintain the shapes yourself in some form. If you're doing GDI+ style drawing, you're just coloring pixels. The Graphics object doesn't know anything about shapes after they are drawn.
Andy West
2009-12-09 07:18:39
+1
A:
You could store the shapes you draw as GraphicsPaths, iterate through them on MouseMove and use IsVisible(Point) to determine when the current mouse position is inside a shape's bounds.
Kevin Wienhold
2009-12-09 07:17:35
Good suggestion. This is a more elegant solution than the one I recommended. Thanks for making me aware of GraphicsPath.
Andy West
2009-12-09 07:23:57
But all the shape I draw is with Graphics.draw (drawrectangle, drawline,etc...) So how can I use GraphicsPath?
Thyphuong
2009-12-09 07:31:07
@Thyphuong: You could create a new GraphicsPath object and use the AddRectangle method to convert your Rectangle into a GraphicsPath. There are Add methods for every shape, so you should be able to convert anything you draw. @Andy West: Thank you and you're welcome.
Kevin Wienhold
2009-12-09 07:58:30
My apologies, I missed the "CF" part of the title and it does seem as if the compact framework doesn't include the GraphicsPath class. In that case you may be stuck with doing hit detection yourself, which is unfortunate. Maybe there are some libraries out there that implement behavior similar to GraphicsPath?
Kevin Wienhold
2009-12-09 09:47:21