c# - 我应该如何从屏幕空间坐标转换为 WinForms PictureBox 中的图像空间坐标?

标签 c# winforms picturebox

我有一个在 Windows 窗体 PictureBox 控件中显示图像的应用程序。控件的 SizeMode 设置为 Zoom,这样 PictureBox 中包含的图像将以纵横比正确的方式显示,而不管PictureBox 的尺寸。

这对于应用程序的视觉外观非常有用,因为您可以根据需要调整窗口大小,并且图像将始终以最适合的方式显示。不幸的是,我还需要处理图片框上的鼠标点击事件,并且需要能够从屏幕空间坐标转换为图像空间坐标。

看起来很容易从屏幕空间转换到控制空间,但我没有看到任何明显的方法从控制空间转换到图像空间(即在图片中缩放的源图像中的像素坐标框)。

有没有一种简单的方法可以做到这一点,还是我应该复制他们在内部使用的缩放数学来定位图像并自己进行翻译?

最佳答案

我最终只是手动实现翻译。代码还不错,但确实让我希望他们直接提供支持。我可以看到这种方法在很多不同的情况下都很有用。

我想这就是他们添加扩展方法的原因:)

在伪代码中:

// Recompute the image scaling the zoom mode uses to fit the image on screen
imageScale ::= min(pictureBox.width / image.width, pictureBox.height / image.height)

scaledWidth  ::= image.width * imageScale
scaledHeight ::= image.height * imageScale

// Compute the offset of the image to center it in the picture box
imageX ::= (pictureBox.width - scaledWidth) / 2
imageY ::= (pictureBox.height - scaledHeight) / 2

// Test the coordinate in the picture box against the image bounds
if pos.x < imageX or imageX + scaledWidth < pos.x then return null
if pos.y < imageY or imageY + scaledHeight < pos.y then return null

// Compute the normalized (0..1) coordinates in image space
u ::= (pos.x - imageX) / imageScale
v ::= (pos.y - imageY) / imageScale
return (u, v)

要获得图像中的像素位置,您只需乘以实际图像像素尺寸,但归一化坐标允许您根据具体情况解决原始响应者关于解决歧义的观点。

关于c# - 我应该如何从屏幕空间坐标转换为 WinForms PictureBox 中的图像空间坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2804/

相关文章:

c# - 领域模型实体与数据实体,软件架构中的一个或两个

c# - 如何在我的所有属性(property)中使用 “distinct”

c# - 组合框值显示选择项目后的结束部分

vb.net - 表单位置 VB.net

c# - 叠加两个或多个位图以在图片框中显示 (C#)

c# - MonoTouch 自动代理网络凭据不起作用

c# - "Resource Monitor"向我展示了比我在程序中编写的两个线程更多的线程

c# 将对象添加到列表框并在其中显示对象字符串

c# - .NET PictureBox - 如何确保资源已释放

C# 随机并一张一张地显示图片