C#圖片適應PictureBox大小顯示


private  Bitmap ResizeImage(Bitmap bmp,PictureBox picBox)
        {
            float xRate =(float) bmp.Width / picBox.Size.Width;
            float yRate = (float)bmp.Height / picBox.Size.Height;
            if (xRate <= 1 && yRate <= 1)
            {
                return bmp;
            }
            else
            {                
                float tRate = (xRate >= yRate) ? xRate : yRate;
                Graphics g = null;
                try
                {
                    int newW = (int)(bmp.Width / tRate);
                    int newH = (int)(bmp.Height / tRate);
                    Bitmap b = new Bitmap(newW, newH);
                    g = Graphics.FromImage(b);
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                    g.Dispose();
                    //bmp.Dispose();
                    return b;
                }
                catch
                {
                    //bmp.Dispose();
                    return null;
                }
                finally
                {
                    if (null != g)
                    {
                        g.Dispose();
                    }
                }
            }
        }

上面的方法返回一個能在PictureBox中完全顯示的圖片。如果希望圖片不變,在特定尺寸的PictureBox中顯示尺寸較大的圖片,可以采用以下方法。
  把   picturebox   放在   panel里面。  
    然后   把   panel的AutoScroll   設置為true,  
    同時你將picturebox   大小設置成   圖片的大小。  
    this.picturebox.width   =   this.image.width  
    this.picturebox.height   =   this.image.height      
  這樣picturebox   大於   panel的時候,就可以用滾動條讓圖片顯示全。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM