Bagikan melalui


Cara: Mengatur Gambar pada Run Time (Formulir Windows)

Anda dapat secara terprogram mengatur gambar yang ditampilkan oleh kontrol Formulir WindowsPictureBox.

Untuk mengatur gambar secara terprogram

  • Atur Image properti menggunakan FromFile metode Image kelas .

    Dalam contoh di bawah ini, jalur yang diatur untuk lokasi gambar adalah folder Dokumen Saya. Ini dilakukan, karena Anda dapat berasumsi bahwa sebagian besar komputer yang menjalankan sistem operasi Windows akan menyertakan direktori ini. Ini juga memungkinkan pengguna dengan tingkat akses sistem minimal untuk menjalankan aplikasi dengan aman. Contoh di bawah ini mengasumsikan formulir dengan kontrol yang PictureBox sudah ditambahkan.

    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"));  
       }  
    

Untuk menghapus grafik

  • Pertama, lepaskan memori yang digunakan oleh gambar, lalu bersihkan grafik. Pengumpulan sampah akan membebaskan memori nanti jika manajemen memori menjadi masalah.

    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;  
    }  
    

    Catatan

    Untuk informasi selengkapnya tentang mengapa Anda harus menggunakan metode dengan Dispose cara ini, lihat Membersihkan Sumber Daya yang Tidak Dikelola.

    Kode ini akan menghapus gambar bahkan jika grafik dimuat ke dalam kontrol pada waktu desain.

Baca juga