图像没跟着变只有一个原因,SizeMode不为Zoom。
微软有提供现成的方法满型握足你的需要。你唯一需要知道的是一个Control的Position是相对于其父容器的边缘而言的,它叫ClientPoint坐标,并非屏幕坐标ScreenPoint。
下面是一个小方法,用来将任意Control的位置置于屏幕正中间。
void SetCenterScreen(Control control)
{
int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
int targetLocationLeft;
哗租谨 int targetLocationTop;
targetLocationLeft = (screenWidth - control.Width) / 2;
targetLocationTop = (screenHeight - control.Height) / 2;
乱基 if (control.Parent != null)
control.Location = control.Parent.PointToClient(new Point(targetLocationLeft, targetLocationTop));
else
control.Location = new Point(targetLocationLeft, targetLocationTop);
}
关于缩放的问题。所有的Control都有Scale方法,接受一个SizeF作为比例因子。
所以你的picturebox事件里应该这样写(每次放大到1.1倍):
pictureBox1.SuspendLayout();
pictureBox1.Scale(new SizeF { Width = 1.1f, Height = 1.1f });
SetCenterScreen(pictureBox1);
pictureBox1.ResumeLayout();
其中,SuspendLayout()是挂起布局引擎,这样会暂时阻止它进行外观和布局上的变更(但是会在自己的Graphics上偷偷画好),直到调用ResumeLayout()时才会一次性的迅速的显示出来。
此外,SizeMode只需要被设置一次,没有必要每次都赋值。
最后补一句,Zoom是“按比例缩放图片”,Strech才是“填满容器”,当然,如果picturebox大小比例和图像宽高比不一致,strech会让图片变形。
在窗体load事型渗件里注册鼠标滚轮事件
private void Form1_Load(object sender, EventArgs e)
{
this.MouseWheel += Form1_MouseWheel;
}
滚轮事件:
void Form1_MouseWheel(object sender, MouseEventArgs e)
{
if (e.Delta > 0) //放大图片
卜磨脊{
pictureBox1.Size = new Size(pictureBox1.Width + 50, pictureBox1.Height + 50);
}
else { //缩小图片
pictureBox1.Size = new Size(pictureBox1.Width - 50, pictureBox1.Height - 50);
}
//设置图片在窗体居中
pictureBox1.Location = new Point((this.Width - pictureBox1.Width) 游局/ 2, (this.Height - pictureBox1.Height) / 2);
}