本文介绍了部分透明图像上的WPF光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含透明区域的png,并将其设置为图像标签,但是当光标位于图像的不透明部分上时,如何将光标设置为手呢?

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?

感谢
Tony

ThanksTony

推荐答案

为此,您需要查看位图本身。 WPF的点击测试机制认为,用透明画笔绘制的任何像素即使不可见也仍然可以单击。这通常是一件好事,但会妨碍您尝试做的事情。因为.png使用透明笔刷绘制,所以在进行命中测试时,整个.png都被视为已绘制。

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.

在 MouseMove 事件处理程序为:


  1. 继续以正常方式调用命中测试。

  2. 对于返回的每个 HitTestResult ,请检查其是否为图片,如果是, ,无论鼠标下方是否有透明像素

  3. 当您击中非图像或图像的非透明像素时,请停止。

  4. 根据鼠标悬停的位置来确定 Cursor 的值

  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. 获取鼠标相对于图像的位置( e.GetPosition(image)

  2. 如果您正在使用拉伸,则必须在此时对拉伸进行反向计算以获得位图索引

  3. 使用 BitmapSource.CopyPixels 将1像素的矩形复制到数组中(即

  4. 检查检索到的像素值是否为透明像素

  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

这篇关于部分透明图像上的WPF光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:32
查看更多