WPF:检测图像仅在非透明部分上单击 [英] WPF: Detect Image click only on non-transparent portion
问题描述
我在WPF中有一个 Image
控件,其中包含一个包含大量透明像素的图像。现在,每当我在图像
上的 MouseDown
事件就会触发>图像控制。我想用某种方法检测鼠标是否发生在图像的不透明部分。
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?
推荐答案
使用这个答案你可以从 Image
派生来创建一个 OpaqueClickableImage
只响应图像的足够不透明区域中的命中测试:
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);
}
}
添加此类后,只需像常规一样使用它image:
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"/>
这篇关于WPF:检测图像仅在非透明部分上单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!