如何:在运行时设置图片(Windows 窗体)

可以以编程方式设置由 Windows 窗体 PictureBox 控件显示的图像。

以编程方式设置图片

  • 使用 Image 类的 FromFile 方法设置 Image 属性。

    在下面的示例中,为图像的位置设置的路径是“我的文档”文件夹。 这样做是因为你可以假定运行 Windows 操作系统的大多数计算机将包含此目录。 这还允许用户使用最少的系统访问级别安全地运行应用程序。 以下示例假定窗体已添加控件 PictureBox

    Private Sub LoadNewPict()  
       ' 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 LoadNewPict(){  
       // 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 LoadNewPict()  
       {  
          // 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"));  
       }  
    

清除图形

  • 首先,释放图像使用的内存,然后清除图形。 如果内存管理出现问题,垃圾回收稍后将释放内存。

    If Not (PictureBox1.Image Is Nothing) Then  
       PictureBox1.Image.Dispose()  
       PictureBox1.Image = Nothing  
    End If  
    
    if (pictureBox1.Image != null)
    {  
       pictureBox1.Image.Dispose();  
       pictureBox1.Image = null;  
    }  
    
    if (pictureBox1->Image != nullptr)  
    {  
       pictureBox1->Image->Dispose();  
       pictureBox1->Image = nullptr;  
    }  
    

    说明

    有关如何以这种方式使用 Dispose 方法的详细信息,请参阅 清理非托管资源

    即使在设计时将图像加载到控件中,此代码也会清除该图像。

另请参阅