图像没跟着变只有一个原因,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会让图片变形。
Pegasus的ImagXpress 8.0控件,支持各种格式文件的加载。控件封装了右键局部区域放大的功能,要实现图片的缩放,把AutoResize属性设置为PegasusImaging.WinForms.ImagXpress8.AutoResizeType.CropImage,修改
ZoomFactor的值就可以了。
以下是简单的图片缩放
Public Class Form1
Dim MapWidth As Integer
Dim MapHeight As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'设置窗体自动添加滚动条
Me.AutoScroll = True
'设置图片框内的图片自动拉伸
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
'加载位图
Dim MapImage As New Bitmap(Application.StartupPath & "\ch4.png", True)
'图片框加载图片
PictureBox1.Image = MapImage
'设置图片框大小
PictureBox1.Size = New Size(MapImage.Width, MapImage.Height)
'记录原始大小
MapWidth = MapImage.Width
MapHeight = MapImage.Height
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Width = PictureBox1.Width * 2
PictureBox1.Height = PictureBox1.Height * 2
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
PictureBox1.Width = PictureBox1.Width / 2
PictureBox1.Height = PictureBox1.Height / 2
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
PictureBox1.Width = MapWidth
PictureBox1.Height = MapHeight
End Sub
End Class