1. 界面设计
pictureBox 调整好大小(不要用dock 属性),sizemode 用 zoom
2. 添加滚轮事件以及焦点
pictureBox1.MouseWheel += new MouseEventHandler(pictureBox1_MouseWheel);
this.ActiveControl = this.pictureBox1; // 设置焦点
注意: 不设置焦点,滚轮不起作用
3. 添加滚轮滚动事件
private double ratio = 1; // 图片的起始显示比例
private double ratioStep = 0.1;
private Size pic_size;
private int xPos;
private int yPos;
pic_size = this.pictureBox1.Size;
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
if (e.Delta > 0)
{
ratio += ratioStep;
if (ratio > 3) // 放大上限
ratio = 3;
else
{
this.changePictureBoxSize(ratio);
}
}
else
{
ratio -= ratioStep;
if (ratio < 0.5) // 放大下限
ratio = 0.5;
else
{
this.changePictureBoxSize(ratio);
}
}
}
private void changePictureBoxSize(double ratio)
{
var t = pictureBox1.Size;
t.Width = Convert.ToInt32(pic_size.Width * ratio);
t.Height = Convert.ToInt32(pic_size.Height * ratio);
pictureBox1.Size = t;
Point location = new Point();
location.Y = (this.Height - this.pictureBox1.Height) / 2;
location.X = (this.Width - this.pictureBox1.Width) / 2;
this.pictureBox1.Location = location;
}
4. 拖动事件
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
try
{
// 鼠标按下拖拽图片
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right)
{
// 限制拖拽出框
if ((pictureBox1.Width - this.Width) >= 0 || (pictureBox1.Height - this.Height) >= 0)
{
if ((pictureBox1.Top + Convert.ToInt16(e.Y - yPos)) <= 0
|| (pictureBox1.Left + Convert.ToInt16(e.X - xPos)) <= 0
|| (pictureBox1.Right + Convert.ToInt16(e.X - xPos)) >= this.Width
|| (pictureBox1.Bottom + Convert.ToInt16(e.Y - yPos)) >= this.Height)
{
pictureBox1.Left += Convert.ToInt16(e.X - xPos);//设置x坐标.
pictureBox1.Top += Convert.ToInt16(e.Y - yPos);//设置y坐标.
}
}
}
}
catch (Exception dd)
{
MessageBox.Show(dd.Message);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
xPos = e.X;//当前x坐标.
yPos = e.Y;//当前y坐标.
}