Reputation: 2615
I’m using WinForms. In my application I have a button that opens a picture in a picture-box. This application is made to zoom in and out of pictures using mouse scroll. I’m able to zoom in and out fine, but my issue is sometimes when I zoom in or zoom out using the scroll wheels in the mouse my application seems to get confused. Confused meaning sometimes for example, if I’m scrolling forward it starts zooming out when it’s supposed to zoom in. I don’t understand what I’m doing wrong in my code for the program to get confused. Is there a better way to zoom in and out or how would I solve this issue?
My code:
int zoomInt = 0;
private void Open_btn_Click(object sender, EventArgs e)
{
Image image;
// open file dialog
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
image = Image.FromFile(open.FileName);
pictureBox1.Image = image;
}
}
protected override void OnMouseWheel(MouseEventArgs e)
{
if (e.Delta > 0)
{
zoomInt++;
if (zoomInt > 4)
{
zoomInt = 4;
}
zoomPicturebox();
}
else if (e.Delta < 0)
{
zoomInt--;
if (zoomInt < -3)
{
zoomInt = -3;
}
zoomPicturebox();
}
}
public void zoomPicturebox()
{
switch (zoomInt)
{
case -3:
this.pictureBox1.Width -= 210; //Zoom width by 210
this.pictureBox1.Height -= 210; //Zoom height by 210
break;
case -2:
this.pictureBox1.Width -= 155; //Zoom width by 155
this.pictureBox1.Height -= 155; //Zoom height by 155
break;
case -1:
this.pictureBox1.Width -= 65; //Zoom width by 75
this.pictureBox1.Height -= 65; //Zoom height by 75
break;
case 0:
pictureBox1.Size = new Size(850, 1100);
break;
case 1:
this.pictureBox1.Width += 75; //Zoom width by 75
this.pictureBox1.Height += 75; //Zoom height by 75
break;
case 2:
this.pictureBox1.Width += 150; //Zoom width by 150
this.pictureBox1.Height += 150; //Zoom height by 150
break;
case 3:
this.pictureBox1.Width += 175; //Zoom width by 175
this.pictureBox1.Height += 175; //Zoom height by 175
break;
case 4:
this.pictureBox1.Width += 200; //Zoom width by 175
this.pictureBox1.Height += 200; //Zoom height by 175
break;
}
pictureBox1.Refresh(); //Helps causing pictures from getting pixialated: Forces the control to invalidate its client area and immediately redraw itself and any child controls
}
Upvotes: 1
Views: 14614
Reputation: 2615
I fixed the issue by deleting the public void zoomPicturebox() method and adding these changes below:
protected override void OnMouseWheel(MouseEventArgs e)
{
if (e.Delta != 0)
{
if (e.Delta <= 0)
{
//set minimum size to zoom
if (pictureBox1.Width < 50)
// lbl_Zoom.Text = pictureBox1.Image.Size;
return;
}
else
{
//set maximum size to zoom
if (pictureBox1.Width > 1000)
return;
}
pictureBox1.Width += Convert.ToInt32(pictureBox1.Width * e.Delta / 1000);
pictureBox1.Height += Convert.ToInt32(pictureBox1.Height * e.Delta / 1000);
}
}
Upvotes: 3