於上一個章節已經學會對會方塊,現在我們使用對話方塊來讀取圖形
Graphics g = this.pictureBox1.CreateGraphics();
Bitmap br = new Bitmap(openFileDialog1.FileName) ;
//放置您所指定的圖片
//並指定圖片要放置的位置,(X,Y) = (0,0)
g.DrawImage(br, 0, 0);
支援的圖檔名稱還真不少,GIF.JPG.JPEG.BMP.WMF.PNG
不過這樣寫有個問題,就是畫面會消失,其他視窗蓋到畫面,圖形就被吃掉了,
用一個簡單的方法解決,建立一個Bimmap 對應到PictureBox.Image
只要PictureBox 被其他視窗擋到,PictureBox 自動重繪的時候就會去Image抓圖,
public partial class Form1 : Form
{
Bitmap buffer;
public Form1()
{
InitializeComponent();
buffer = new Bitmap(pictureBox1.Width, pictureBox1.Height );
}
private void OpenFileButton_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "逼恩批|*.bmp|傑批居|*.jpg|批恩居|*.png"; //檔案過濾器
openFileDialog1.Multiselect = false; //取消多從選擇 = 單選
openFileDialog1.InitialDirectory = Application.StartupPath; //程式啟動路徑,為預設路徑
openFileDialog1.FileName = ""; //清除預設檔名
openFileDialog1.ShowDialog(); //顯示對話方塊
if (openFileDialog1.FileName.Equals( "" ))
{
MessageBox.Show("取消選取" );
}
else
{
buffer = new Bitmap(openFileDialog1.FileName);
//放置您所指定的圖片
//並指定圖片要放置的位置,(X,Y) = (0,0)
pictureBox1.Width = buffer.Width;
pictureBox1.Height = buffer.Height;
pictureBox1.Image = buffer;
}
}
}
沒有留言:
張貼留言