代码之家  ›  专栏  ›  技术社区  ›  fastcall

如何在WinForms PictureBox中从屏幕空间坐标转换为图像空间坐标?

  •  13
  • fastcall  · 技术社区  · 16 年前

    PictureBox 控制这个 SizeMode 控件的属性设置为 Zoom 图片框 将以正确的方式显示,而不考虑屏幕的尺寸 图片框

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

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

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

    2 回复  |  直到 13 年前
        1
  •  6
  •   fastcall    15 年前

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

    在伪代码中:

    // 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)
    

        2
  •  2
  •   tags2k    16 年前

    根据缩放比例,相对图像像素可以是多个像素中的任意位置。例如,如果图像被显著缩小,像素2,10可能代表2,10(一直到20,100),因此您必须自己进行计算,并对任何不准确之处承担全部责任!:-)