如何在控件上显示图像

多个 Windows 窗体控件可以显示图像。 这些图像可以是阐明控件用途的图标,例如表示“保存”命令的按钮上的磁盘图标。 或者,图标可以是背景图像,以便为控件提供所需的外观和行为。

显示图像 - 设计器

在 Visual Studio 中,使用视觉设计器显示图像。

  1. 打开包含待更改控件的表单的视觉设计器。

  2. 选择控件。

  3. 在“属性”窗格中,选择控件的 图像BackgroundImage 属性。

  4. 选择省略号()以显示 “选择资源”对话框,然后选择要显示的图像。

    属性对话框,其中选择了图像属性

显示图像 - 代码

将控件的 ImageBackgroundImage 属性设置为 Image类型的对象。 通常,你将使用 FromFile 方法从文件加载映像。

在以下代码示例中,为图像位置设置的路径是“我的图片” 文件夹 。 运行 Windows 操作系统的大多数计算机都包含此目录。 这也使系统访问级别最少的用户能够安全地运行应用程序。 下面的代码示例要求你已具有一个添加了 PictureBox 控件的窗体。

// Replace the image named below with your own icon.
// Note the escape character used (@) when specifying the path.
pictureBox1.Image = Image.FromFile
   (System.Environment.GetFolderPath
   (System.Environment.SpecialFolder.MyPictures)
   + @"\Image.gif");
' Replace the image named below with your own icon.
PictureBox1.Image = Image.FromFile _
   (System.Environment.GetFolderPath _
   (System.Environment.SpecialFolder.MyPictures) _
   & "\Image.gif")

另请参阅