从位图的非透明区域创建 Region 或 GraphicsPath
我想对绘制的位图进行命中测试,以查看给定的点在图像的非透明像素中是否可见。
例如,要对整个位图矩形进行此测试,您可以执行以下操作:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
恕我直言,一种更简单的技术是查看命中像素的 alpha 分量:
IMHO a simpler technique would be to look at the alpha component of the hit pixel: