使用平移和缩放计算正确的光标位置

我现在一直在搞乱这个问题大约一个小时。

我有一个支持平移和缩放的视口,通过存储X和Y轴的偏移来处理平移。 变焦只是从0.2到14的浮动。

我的问题是我需要能够放置用户在视口中点击的东西,但是当我缩放和平移时鼠标坐标不正确。 我无法弄清楚如何正确计算鼠标坐标。

这是一张显示我目前所拥有的图片: http : //i.imgur.com/WQSXKJ2.png

如您所见,鼠标原点始终位于视口组件的左上角。 您可以在图像的左下角看到平移X和Y偏移以及缩放值。 我还添加了一个与视口左上角相关的鼠标坐标示例。

现在,因为在该图像中它当前放大了我放置的对象将被偏移。

感谢您的时间!

编辑为我的案例工作的解决方案:

void Viewport_MouseClick(object sender, MouseEventArgs e){ Point mousePosition = new Point((int)((eX - Pan.X) / Zoom), (int)((eY - Pan.Y) / Zoom)); } 

这会计算出正确的“屏幕空间”鼠标位置,同时考虑平移和缩放。 我通过玩TaWs答案得到了解决方案。 感谢您的帮助! 🙂

使用TrackBar进行缩放以及另外两个用于偏移,这似乎有效:

 private void panel1_Paint(object sender, PaintEventArgs e) { using (Bitmap bmp = new Bitmap(filename)) { e.Graphics.ScaleTransform(zoom, zoom); e.Graphics.DrawImage(bmp, trb_offsetX.Value, trb_offsetY.Value); } } float zoom = 1f; private void panel1_MouseMove(object sender, MouseEventArgs e) { Point mouseLocation = e.Location; Point imageLocation = new Point((int)((mouseLocation.X / zoom - trb_offsetX.Value)), (int)((mouseLocation.Y / zoom - trb_offsetY.Value))); st_mousePos.Text = " " + imageLocation.ToString(); } private void trackBar1_Scroll(object sender, EventArgs e) { zoom = trackBar1.Value; panel1.Invalidate(); } 

我已经为Paint事件添加了代码,因此您可以看到这是否也是您处理它的方式。

将图片放入PictureBox,然后计算鼠标的相对位置。 那是

  double Pic_width = orginal_image_width/ pictureBox.width; double Pic_height = orginal_image_height/ pictureBox.height; var mouseArgs = (MouseEventArgs)e; int xpoint = Convert.ToInt16(mouseArgs.X * Pic_width); int ypoint = Convert.ToUInt16(mouseArgs.Y * Pic_height); 

此代码将为您提供光标在图像中的位置。