要求:在鼠标指着图像时,按住ctrl时,滚轮往前滚,图像放大,滚轮往后滚,图像缩小,同时,
鼠标没有在图像区域时,或者没有按住ctrl时,不得执行缩放。
缩放倍率必须有最小值和最大值。
思路:①因为winform的pictureBox控件没有滚轮事件,所以需要自己创建。
②将pictureBox放入panel中
③更新图像位置
④控制缩放比例
⑤光标位置不能变化——>先缩放,再进行位移
⑥优化精度
public partial class Form1 : Form
{
private const float MIN_zoom = 100;//最小宽度
private const float MAX_zoom = 1000;//最大宽度
float step = 1.1f;//缩放倍率
public Form1()
{
InitializeComponent();//当滚轮滚动时,图像会围绕这个点缩放
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
}
private void PictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
if (Control.ModifierKeys == Keys.Control)
{
if ( e.Delta > 0)
{
if (pictureBox1.Width < MAX_zoom)//给宽度设置最大值
{
// 设置pictureBox1的宽度和高度以反映新的缩放比例
pictureBox1.Width = (int)(pictureBox1.Width * step);
pictureBox1.Height = (int)(pictureBox1.Height * step);
double px = e.X - panel1.Location.X;
double py = e.Y - panel1.Location.Y;
double px_add = (double)(px * (step - 1.0));
double py_add = (double)(py * (step - 1.0));
//图片往左上移动坐标是减
pictureBox1.Location = new Point((int)(pictureBox1.Location.X - px_add), (int)(pictureBox1.Location.Y - py_add));
Application.DoEvents();
}
}
else if (e.Delta < 0)
{
if (pictureBox1.Width > MIN_zoom)//给宽度设置最小值
{
pictureBox1.Height = (int)(pictureBox1.Height / step);
pictureBox1.Width = (int)(pictureBox1.Width / step);
double px = e.X - panel1.Location.X;
double py = e.Y - panel1.Location.Y;
double px_add = (int)(px * (1.0 - 1.0 / step));
double py_add = (int)(py * (1.0 - 1.0 / step));
//图片往右下移动坐标是加
pictureBox1.Location = new Point((int)(pictureBox1.Location.X + px_add),(int) (pictureBox1.Location.Y + py_add));
Application.DoEvents();
}
}
}
}
}