用C#做圖片瀏覽器

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

      用C#作圖片瀏覽器還是相當(dāng)方便的,或者說(shuō)C#用來(lái)開(kāi)發(fā)winform還是相當(dāng)強(qiáng)大的,撇去性能不說(shuō)。做出了一個(gè)簡(jiǎn)單的圖片瀏覽器:

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

      先建一個(gè)用來(lái)顯示圖形的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類中,改寫(xiě)Dispose方法如下:

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

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

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

                //實(shí)例化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;
            }
        }

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

關(guān)鍵詞:C#

贊助商鏈接: