我正在使用WinForms。在我的应用程序中,我有一个按钮,可以在图片框中打开图片。此应用程序使用鼠标滚动放大和缩小图片。我能够放大和缩小,但我的问题有时当我使用鼠标中的滚轮放大或缩小时,我的应用程序似乎感到困惑。有时混淆的含义,例如,如果我向前滚动它会在它应该放大时开始缩小。我不明白我的代码中我做错了什么让程序感到困惑。是否有更好的放大和缩小方法或如何解决此问题?
我的代码:
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
}
答案 0 :(得分:1)
我通过删除public void zoomPicturebox()方法并在下面添加以下更改来修复此问题:
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);
}
}