How to do Hit testing in GDI+ for rotated shapes with real shape measurements (inches)?

守給你的承諾、 提交于 2019-12-04 13:42:23

问题


Given I have a canvas that contains many shapes, lets say rectangles for now.

Each shape has a location (inches), size(inches) and rotation angle(degrees).

When a mouse click event happen inside the canvas for a location (x,y) in pixels.

I want to check if the clicked mouse position is inside/within a specific shape, considering the rotation angle and measurement unit conversion.

Can you help?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/438335/how-to-do-hit-testing-in-gdi-for-rotated-shapes-with-real-shape-measurements-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!