从位图的非透明区域创建 Region 或 GraphicsPath

发布于 2024-12-07 05:25:02 字数 701 浏览 1 评论 0原文

我想对绘制的位图进行命中测试,以查看给定的点在图像的非透明像素中是否可见。

例如,要对整个位图矩形进行此测试,您可以执行以下操作:

Bitmap bitmap = new Bitmap("filename.jpg");
GraphicsPath path = new GraphicsPath();
Rectangle bitmapRect = new Rectangle(x, y, bitmap.Width, bitmap.Height);

path.AddRectangle(bitmapRect);

if (path.IsVisible(mouseLocation))
    OnBitmapClicked();

但是,如果我有一个非矩形项目的位图,并且我希望能够检查它们是否正在单击不透明的项目区域,.NET 框架中有没有支持的方法来做到这一点?

我想到的唯一方法是将位图字节锁定到一个数组中,然后迭代它,将每个不透明的 x,y 坐标添加到 Point 结构数组中。然后使用这些点结构来组装 GraphicsPath。

由于这些点是从零开始的,所以我需要将鼠标位置偏移到绘制图像的 x,y 坐标和 0,0 之间的距离。但这样,如果我多次绘制每个图像,只要图像没有倾斜或缩放不同,我基本上可以对每个图像使用相同的 GraphicsPath。

如果这是唯一的好路线,我如何将点添加到 GraphicsPath 中?从点到点画线?画一条闭合曲线?

I want to hit-test a drawn bitmap to see if a given Point is visible in the non-transparent pixels of the image.

For example, to do this test for the whole bitmap rectangle, you would do something like this:

Bitmap bitmap = new Bitmap("filename.jpg");
GraphicsPath path = new GraphicsPath();
Rectangle bitmapRect = new Rectangle(x, y, bitmap.Width, bitmap.Height);

path.AddRectangle(bitmapRect);

if (path.IsVisible(mouseLocation))
    OnBitmapClicked();

However, if I have a bitmap of a non-rectangular item and I want to be able to check if they are clicking on the non-transparent area, is there any supported way in the .NET framework to do this?

The only way I could think to do this is to lock the bitmap bytes into an array, and iterate through it, adding each x,y coordinate that is non-transparent to an array of Point structures. Then use those point structures to assemble a GraphicsPath.

Since these points would be zero-based I would need to offset my mouse location with the distance between the x,y coordinate that the image is being drawn at and 0,0. But this way I could essentially use the same GraphicsPath for each image if I draw it multiple times, as long as the image is not skewed or scaled differently.

If this is the only good route, how would I add the points to the GraphicsPath? Draw lines from point to point? Draw a closed curve?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆梦 2024-12-14 05:25:02

恕我直言,一种更简单的技术是查看命中像素的 alpha 分量:

Color pixel = bitmap.GetPixel(mouseLocation.X, mouseLocation.Y);
bool hit = pixel.A > 0;

IMHO a simpler technique would be to look at the alpha component of the hit pixel:

Color pixel = bitmap.GetPixel(mouseLocation.X, mouseLocation.Y);
bool hit = pixel.A > 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文