views:

715

answers:

3

I have a canvas that contains many shapes and every shape has a location, size and rotation angle (size and location are in inches) and I want to check if mouse position is within which shape (the rotated shape) ?? can anyone help?

+2  A: 

Check this article on testing point in triangle. It is the best material I have found on this topic.

Marcin Gil
+3  A: 

Your question is awfully short on details, I can only provide a generic answer. Do it mathematically is the fastest way. Rotation can make that difficult.

You can solve it slowly but easily by using a hit-test bitmap. Render the shapes to a Bitmap, using the same code you now use to render it to the screen. But now using a color that encodes the shape number. Hit testing is now simple and quick with GetPixel(). Be careful to turn off image enhancement settings, like anti-aliasing. Render it to the screen first and take a good look at the pixels with ZoomIt.

Hans Passant
I was about to give a similar answer, it is the best solution for arbitrarily shaped objects (or sprites!).
PhiLho
this will become very very slow if my canvas contains hundreds of shapes
Code Guru
It will be exactly as slow as painting them to the screen. Of course, you make the bitmap only once, not over and over again. Like you did in your post that you marked as the answer.
Hans Passant
+1  A: 

I found the answer (I have to convert al measurements to pixels to make sure it will calculate correctly):

public static bool HitTest(Rectangle bounds, float angle, Point location)
        {
            if (angle == 0) return bounds.Contains(location);

            using (Matrix matrix = new Matrix())
            {
                matrix.RotateAt(angle, Center(bounds));
                using (GraphicsPath path = new GraphicsPath())
                {
                    path.AddRectangle(bounds);
                    path.Transform(matrix);
                    return path.IsVisible(location.X, location.Y);
                }
            }
        }
Code Guru