views:

540

answers:

2

Pls help! i am trying to make a zoom effect on a picturebox by mouse wheel.Everything is ok except that when i use mouse middle button to zoom in or zoom out it is ok but it does not zoom in or zoom out the point which the mouse cursor on.when i zoom in the point what i want it always slide .Pls help me to add a snippet code to make it right working. Here is my code. I am trying to make a zoom effect on a picturebox by mouse wheel. Everything is ok except that when I use mouse middle button to zoom in or zoom out it is ok but it does not zoom in or zoom out the point which the mouse cursor on.

When I zoom in the point what I want it always slide. Please help me to add a snippet code to make it right working.

Here is my code:

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);
}
A: 

You are not taking the mouse coordinates into account.

The MouseEventArgs class tells you where the mouse is (X, Y and Location properties), so you need to adjust accordingly.

Oded
A: 

You need to adjust the picture box location based on the mouse position relative to the form.

Here is a rough but working example of how you might do this:

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();
Nathan Baulch
What's the point of having real data types when you can just use "var" everywhere nowadays...? I didn't even know you could use var in C# I've never seen it before except for the past week or so...
lucifer
var is a "real data type" it's just implicitly typed
Eric
Thanks it is really helpful but this time i need something like an animation when zoom in or zoom out to please the eye.