在图像的实际大小中获取鼠标的真实位置,而不是在PictureBox中获取鼠标的位置

3

我有一张1278 X 958像素大小的图片,需要进行一些图像处理。

由于图片尺寸较大,在pictureBox中加载时使用以下命令:

imGrayShow = cap.QueryGrayFrame();
picBOriginal.Image = imGrayShow.ToBitmap();

pictureBox的尺寸为299 X 204,而我想在其中查看我的原始图片,于是我使用了pictureBox Size Mode=StretchImage

故事从这里开始:

我想使用鼠标按下和鼠标释放事件来获得用户选择区域的位置,命令如下:

 private void picBOriginal_MouseUp(object sender, MouseEventArgs e)
        {
            if (stopEventMouseDrag == true)
            {
                endP = e.Location;

                if (startP != endP)
                {
                    stopEventMouseDrag = false;
                }
            }
        }

        private void picBOriginal_MouseDown(object sender, MouseEventArgs e)
        {
            if (stopEventMouseDrag == true)
            {
                startP = e.Location;
            }
        }

我得到的 startPendP 是分别为 (145,2)(295,83),但这些是在 pictureBox 上鼠标的位置,而我希望找到鼠标在原始图像中按下时的真实位置(即: startP: 890,1 endP: 1277,879)。如何才能获得在原始图像中的 startP-endP 的真实位置呢?
2个回答

4
我认为你的数学有点问题。如果你有一张1278 x 958的图片,并且想将其缩小到299像素宽,那么你需要将所有值除以 1278 / 299,即4.27。为保持纵横比不变,宽度需要是 958 / 4.27,约为224
然后,当你从鼠标按下和抬起事件中接收到坐标时,只需将坐标乘以4.27来将值缩放到原始图像。

这很整洁,如果我保持我的pictureSizeMode为stretchImage,还可以吗? - farzin parsa
David所说的内容有所补充。宽度的乘法因子为4.27,高度的乘法因子为4.69。 - Sivaraman

1

startP和endP是相对于您的图片框还是相对于屏幕的点?据我所记,MouseEventArgs中的Location是相对于窗体的,这并不是很有用。

因此...它可能会变成这样:

// Position of the mouse, relative to the upper left corner of the picture box.
Point controlRelative = myPictureBox.PointToClient(MousePosition);
// Size of the image inside the picture box
Size imageSize = myPictureBox.Image.Size;
// Size of the picture box
Size boxSize = myPictureBox.Size;

Point imagePosition = new Point((imageSize.Width / boxSize.Width) * controlRelative.X,
                                (imageSize.Height / boxSize.Height) * controlRelative.Y);

好的,该事件假定pictureBox区域,因此它是相对于pictureBox的。 - farzin parsa
然后,只需跳过第一行并在最后一行中使用事件数据。 - LightStriker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接