如何:在執行階段設定圖片 (Windows Form)
您可以透過程式設計方式設定 Windows Forms 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 方法的詳細資訊,請參閱 清除 Unmanaged 資源 。
即使圖形在設計階段載入控制項,此程式碼也會清除影像。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應