Pergunta

I want to hit-test a drawn bitmap to see if a given Point is visible in the non-transparent pixels of the image.

For example, to do this test for the whole bitmap rectangle, you would do something like this:

Bitmap bitmap = new Bitmap("filename.jpg");
GraphicsPath path = new GraphicsPath();
Rectangle bitmapRect = new Rectangle(x, y, bitmap.Width, bitmap.Height);

path.AddRectangle(bitmapRect);

if (path.IsVisible(mouseLocation))
    OnBitmapClicked();

However, if I have a bitmap of a non-rectangular item and I want to be able to check if they are clicking on the non-transparent area, is there any supported way in the .NET framework to do this?

The only way I could think to do this is to lock the bitmap bytes into an array, and iterate through it, adding each x,y coordinate that is non-transparent to an array of Point structures. Then use those point structures to assemble a GraphicsPath.

Since these points would be zero-based I would need to offset my mouse location with the distance between the x,y coordinate that the image is being drawn at and 0,0. But this way I could essentially use the same GraphicsPath for each image if I draw it multiple times, as long as the image is not skewed or scaled differently.

If this is the only good route, how would I add the points to the GraphicsPath? Draw lines from point to point? Draw a closed curve?

Foi útil?

Solução

IMHO a simpler technique would be to look at the alpha component of the hit pixel:

Color pixel = bitmap.GetPixel(mouseLocation.X, mouseLocation.Y);
bool hit = pixel.A > 0;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top