用C#做圖片瀏覽器

2010-08-28 10:49:35來源:西部e網(wǎng)作者:

      用C#作圖片瀏覽器還是相當(dāng)方便的,或者說C#用來開發(fā)winform還是相當(dāng)強大的,撇去性能不說。做出了一個簡單的圖片瀏覽器:

      GDI+自己封裝了相當(dāng)多的功能,使得圖形編程比GDI方便了很多,用MFC可能要寫的很多代碼,用C#只要簡單的一些就能實現(xiàn)。下面是過程和部分代碼:

      先建一個用來顯示圖形的form(此處名為picture),并添加代碼如下:

    public partial class Picture : Form
    {
        public Image image1;
        public string filename = "";
        public void SetFilename(string filename1)
        {
            this.filename = filename1;
        }

        public Picture()
        {
            InitializeComponent();
            {
                this.components = new System.ComponentModel.Container();
            }
        }      

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics gp = e.Graphics;
            gp.DrawImageUnscaled(image1, this.AutoScrollPosition);
            base.OnPaint(e);
        }

      picuture 的designer類中,改寫Dispose方法如下:

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
            image1.Dispose();
        }

      建立picture的MDI父窗體MainForm,關(guān)鍵是改寫OpenFile方法如下:

 private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //定位初始目錄
            if (flag==false)
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //設(shè)置圖片文件類型過濾
            openFileDialog.Filter = " JPEG files (*.jpg)|*.jpg|位圖(*.bmp)|*.bmp|GIF files (*.gif)|*.gif|所有文件(*.*)|*.*";
           
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                FileName = openFileDialog.FileName;

                //實例化picture Form
                Picture childForm = new Picture();
                childForm.MdiParent = this;
                childForm.SetFilename(FileName);
                childForm.image1 = Image.FromFile(FileName);
                //childForm.Size = new System.Drawing.Size(800,600);
                childForm.Size = childForm.image1.Size;
                childForm.AutoSize = false;
                childForm.AutoScale = true;
                childForm.AutoScrollMinSize = childForm.image1.Size;
                childForm.Text = FileName;
                //顯示圖片
                childForm.Show();

                //定位初始目錄到當(dāng)前目錄
                string filepath=FileName.Substring( 0,FileName.LastIndexOf(@"\") );
                openFileDialog.InitialDirectory = filepath;
                flag = true;
            }
        }

      這是一個功能很簡單的圖片瀏覽器。(許多功能還都需要自己慢慢添加,這只是一個開頭和思路。)

關(guān)鍵詞:C#

贊助商鏈接: