views:

310

answers:

2

I have a png that contains transparent regions and I set it to the image tag but how am I able to set the cursor to a hand when it is over an opaque part of the image?

Thanks Tony

+1  A: 

To do this you will need to look at the bitmap itself. WPF's hit testing mechanism considers any pixel painted ith a "transparent" brush to still be clickable even though invisible. This is normally a good thing but gets in the way of what you're trying to do. Because a .png paints with the transparent brush, the entire .png is considerd as painted when doing hit testing.

What you need to do in your MouseMove event handler is:

  1. Go ahead and invoke hit testing the normal way.
  2. For each HitTestResult you get back, check to see if it is an Image and if so, whether a transparent pixel is under the mouse
  3. When you get a hit on a non-image or a non-transparent pixel of an image, stop.
  4. Decide on a Cursor value based on what the mouse is over

To determine whether a the mouse is over a transparent pixel of an image:

  1. Get the mouse position relative to the image (e.GetPosition(image))
  2. If you're using stretching you must back-compute the stretch at this point to get a bitmap index
  3. Use BitmapSource.CopyPixels to copy a 1-pixel rectangle into an array (ie. only the single pixel the mouse is over)
  4. Check the pixel value that was retrieved to see if it is a transparent pixel
Ray Burns
This is pretty much what I did and works brilliantly.
TWith2Sugars
A: 

Can either of you two post some source on a solution here? I'm having an issue on determining if a pixel is transparent or not. I'm following along fine up to that point. Thanks!

csciguy
I'm not at work until Monday so if you can wait until then I'l post it. :D
TWith2Sugars
Sorry for the delay - I completely forgot; Here is a link to the code I use: http://blog.tonywilliams.me.uk/post/392778744/find-the-transparent-pixels-in-an-image-wpf
TWith2Sugars