WPF: Detect Image click only on non-transparent portion

后端 未结 2 1191
無奈伤痛
無奈伤痛 2020-12-19 04:54

I have an Image control in WPF which contains an image with lots of transparent pixels. Right now, the MouseDown event on Image fires

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 05:28

    public class OpaqueClickableImage : Image
    {
        protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
        {
            var source = (BitmapSource)Source;
            var x = (int)(hitTestParameters.HitPoint.X / ActualWidth * source.PixelWidth);
            var y = (int)(hitTestParameters.HitPoint.Y / ActualHeight * source.PixelHeight);
            if (x == source.PixelWidth)
                x--;
            if (y == source.PixelHeight)
                y--;
            var pixels = new byte[4];
            source.CopyPixels(new Int32Rect(x, y, 1, 1), pixels, 4, 0);
            if (pixels[3] < 1) return null;
            return new PointHitTestResult(this, hitTestParameters.HitPoint);
        }
    }
    

提交回复
热议问题