试图制作缩放效果

时间:2010-03-12 10:40:47

标签: c# winforms zoom mousewheel

我正在尝试使用鼠标滚轮在图片框上进行缩放效果。一切都很好,除了当我使用鼠标中键放大或缩小时,没关系,但它不会放大或缩小鼠标光标所在的点。当我放大点时,我希望它总是滑动。请帮我添加一个代码段以使其正常工作。

这是我的代码:

int i = 5;
int index = 10;
private double[] zoomfactor = { .25, .33, .50, .66, .80, 1, 1.25, 1.5, 2.0, 2.5, 3.0 };

private void Zoom(int i)
{

  double new_Zoom = zoomfactor[i];

  imgBox.Width = Convert.ToInt32(imgBox.Image.Width * new_Zoom);
  imgBox.Height = Convert.ToInt32(imgBox.Image.Height * new_Zoom);

}

private void On_wheel(object sender, System.Windows.Forms.MouseEventArgs e)
{
  i = i + e.Delta / 120;
  if (i < 0)
  {
    i = 0;
  }
  else
  {
    if (i <= index)
      i = i;
    else
      i = index;
   }
   Zoom(i);
}

2 个答案:

答案 0 :(得分:2)

您需要根据相对于表单的鼠标位置调整图片框位置。

以下是如何执行此操作的粗略但有效的示例:

var i = 5;
var zoomfactor = new[] {.25, .33, .50, .66, .80, 1, 1.25, 1.5, 2.0, 2.5, 3.0};
var origin = new Point(100, 100);
var image = Image.FromFile(@"c:\example.png");
var imgBox = new PictureBox {
        Location = origin,
        Size = image.Size,
        Image = image,
        SizeMode = PictureBoxSizeMode.StretchImage
    };
var form = new Form {
        Size = new Size(800, 600),
        Controls = {imgBox}
    };
form.MouseWheel += (sender, e) => {
        i += e.Delta/120;
        if (i < 0) {
            i = 0;
        }
        if (i >= zoomfactor.Length) {
            i = zoomfactor.Length - 1;
        }
        var newZoom = zoomfactor[i];
        imgBox.Width = (int) (imgBox.Image.Width*newZoom);
        imgBox.Height = (int) (imgBox.Image.Height*newZoom);
        imgBox.Left = (int) (e.X - newZoom*(e.X - origin.X));
        imgBox.Top = (int) (e.Y - newZoom*(e.Y - origin.Y));
    };
form.ShowDialog();

答案 1 :(得分:0)

您没有考虑鼠标坐标。

MouseEventArgs类会告诉您鼠标的位置(XYLocation属性),因此您需要进行相应的调整。