Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Detect Image click only on non-transparent portion

I have an Image control in WPF which contains an image with lots of transparent pixels. Right now, the MouseDown event on Image fires whenever I click within the full rectangular region of the Image control. I would like some way to detect if the mouse click occurred on a nontransparent portion of the image.

What would be the best way of doing this?

like image 906
Bradley Avatar asked Jan 26 '11 01:01

Bradley


1 Answers

Using the technique in this answer you can derive from Image to create an OpaqueClickableImage that only responds to hit-testing in sufficiently non-transparent areas of the image:

public class OpaqueClickableImage : Image
{
    protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
    {
        var source = (BitmapSource)Source;

        // Get the pixel of the source that was hit
        var x = (int)(hitTestParameters.HitPoint.X / ActualWidth * source.PixelWidth);
        var y = (int)(hitTestParameters.HitPoint.Y / ActualHeight * source.PixelHeight);

        // Copy the single pixel into a new byte array representing RGBA
        var pixel = new byte[4];
        source.CopyPixels(new Int32Rect(x, y, 1, 1), pixel, 4, 0);

        // Check the alpha (transparency) of the pixel
        // - threshold can be adjusted from 0 to 255
        if (pixel[3] < 10)
            return null;

        return new PointHitTestResult(this, hitTestParameters.HitPoint);
    }
}

after adding this class, just use it like a regular image:

<utils:OpaqueClickableImage Name="image" Source="http://entropymine.com/jason/testbed/pngtrans/rgb8_t_bk.png" Stretch="None"/>
like image 196
Rick Sladkey Avatar answered Nov 15 '22 23:11

Rick Sladkey