如何使用该图像上的鼠标位置放大

我有一个userControl库,它包含主Panel和PictureBox,我想制作一个可缩放的PictureBox工具,我使用主面板的mouseWheel事件放大和缩小,我无法弄清楚我怎么办的问题放大图像上的鼠标位置,因此每当我放大时,缩放都会进入面板的左上角,那么我该如何解决?

private double ZOOMFACTOR = 1.15; // = 15% smaller or larger private int MINMAX = 5; void picPanel_MouseWheel(object sender, MouseEventArgs e) { if (e.Delta > 0) { ZoomIn(); } else { ZoomOut(); } } private void ZoomIn() { if ((picBox.Width < (MINMAX * this.Width)) && (picBox.Height < (MINMAX * this.Height))) { picBox.Width = Convert.ToInt32(picBox.Width * ZOOMFACTOR); picBox.Height = Convert.ToInt32(picBox.Height * ZOOMFACTOR); } } private void picBox_MouseEnter(object sender, EventArgs e) { if (picBox.Focused) return; picBox.Focus(); } 

更新:

我试过这个,它看起来像工作,但不完全应该是! 有任何想法吗?

  private void ZoomIn() { if ((picBox.Width < (MINMAX * this.Width)) && (picBox.Height < (MINMAX * this.Height))) { picBox.Width = Convert.ToInt32(picBox.Width * ZOOMFACTOR); picBox.Height = Convert.ToInt32(picBox.Height * ZOOMFACTOR); Point p = this.AutoScrollPosition; int deltaX = eX - pX; int deltaY = eY - pY; this.AutoScrollPosition = new Point(deltaX, deltaY); } } 

这是在鼠标位置放大图像的例子….测试非常.. Mrittunjay Sharma 9599720337

 protected override void OnMouseWheel(MouseEventArgs ea) { // flag = 1; // Override OnMouseWheel event, for zooming in/out with the scroll wheel if (picmap1.Image != null) { // If the mouse wheel is moved forward (Zoom in) if (ea.Delta > 0) { // Check if the pictureBox dimensions are in range (15 is the minimum and maximum zoom level) if ((picmap1.Width < (15 * this.Width)) && (picmap1.Height < (15 * this.Height))) { // Change the size of the picturebox, multiply it by the ZOOMFACTOR picmap1.Width = (int)(picmap1.Width * 1.25); picmap1.Height = (int)(picmap1.Height * 1.25); // Formula to move the picturebox, to zoom in the point selected by the mouse cursor picmap1.Top = (int)(ea.Y - 1.25 * (ea.Y - picmap1.Top)); picmap1.Left = (int)(ea.X - 1.25 * (ea.X - picmap1.Left)); } } else { // Check if the pictureBox dimensions are in range (15 is the minimum and maximum zoom level) if ((picmap1.Width > (imagemappan.Width)) && (picmap1.Height > (imagemappan.Height))) {// Change the size of the picturebox, divide it by the ZOOMFACTOR picmap1.Width = (int)(picmap1.Width / 1.25); picmap1.Height = (int)(picmap1.Height / 1.25); // Formula to move the picturebox, to zoom in the point selected by the mouse cursor picmap1.Top = (int)(ea.Y - 0.80 * (ea.Y - picmap1.Top)); picmap1.Left = (int)(ea.X - 0.80 * (ea.X - picmap1.Left)); } } } } 

问题是你的控件就像一个视口 – 原点是左上角,所以每次你拉伸你从那个角落做的图像时 – 结果是你最后放大到左上角,你需要偏移拉伸的图像并使用户放大的点居中。

  • 图像大小:200,200
  • 用户单击100,50并放大x2
  • 拉伸图像
  • 图像大小为400,400,用户点击的位置现在实际上为200,100
  • 你需要将图像向左滑动100像素,向上滑动50像素以校正重新调整图像大小

您需要覆盖paint事件处理程序以绘制图像偏移量:

  RectangleF BmpRect = new RectangleF((float)(Offset.X), (float)(Offset.Y), (float)(ZoomedWidth), (float)(ZoomedHeight)); e.Graphics.DrawImage(Bmp, ViewPort , BmpRect, GraphicsUnit.Pixel); 

Bmp是你的形象; ViewPort是由pictureBox控件定义的Rectangle

这是一个可能有用的线程 。