如何:在运行时修改图片的大小或位置(Windows 窗体)
如果在窗体上使用 Windows 窗体 PictureBox 控件,则可以将 SizeMode 属性设置为:
将图片的左上角与控件的左上角对齐
在控件内居中图片
调整控件的大小以适应它显示的图片
拉伸显示的任何图片以适应控件
拉伸图片(尤其是位图格式的图片)可能会降低图像质量。 图元文件是在运行时用于绘制图像的图形指令列表,比位图更适合拉伸。
在运行时设置 SizeMode 属性
将 SizeMode 设置为 Normal(默认值)、AutoSize、CenterImage或 StretchImage。 Normal 表示图像放置在控件的左上角;如果图像大于控件,则其下边缘和右边缘被剪裁。 CenterImage 表示图像在控件中居中,如果图像大于控件,则图像的外部边缘会被裁剪。 AutoSize 意味着控件的大小调整为图像的大小。 StretchImage 与之相反,表示将图像的大小调整为控件的大小。
在下面的示例中,为图像的位置设置的路径是“我的文档”文件夹。 这样做是因为你可以假定运行 Windows 操作系统的大多数计算机将包含此目录。 这还允许用户使用最少的系统访问级别安全地运行应用程序。 以下示例假定窗体已添加控件 PictureBox。
Private Sub StretchPic() ' Stretch the picture to fit the control. PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage ' Load the picture into the control. ' You should replace the bold image ' in the sample below with an icon of your own choosing. PictureBox1.Image = Image.FromFile _ (System.Environment.GetFolderPath _ (System.Environment.SpecialFolder.Personal) _ & "\Image.gif") End Sub
private void StretchPic(){ // Stretch the picture to fit the control. PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; // Load the picture into the control. // You should replace the bold image // in the sample below with an icon of your own choosing. // Note the escape character used (@) when specifying the path. PictureBox1.Image = Image.FromFile _ (System.Environment.GetFolderPath _ (System.Environment.SpecialFolder.Personal) _ + @"\Image.gif") }
private: void StretchPic() { // Stretch the picture to fit the control. pictureBox1->SizeMode = PictureBoxSizeMode::StretchImage; // Load the picture into the control. // You should replace the bold image // in the sample below with an icon of your own choosing. pictureBox1->Image = Image::FromFile(String::Concat( System::Environment::GetFolderPath( System::Environment::SpecialFolder::Personal), "\\Image.gif")); }