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的时候,就可以用滚动条让图片显示全。

posted on 2012-04-19 13:33  Hexy  阅读(15786)  评论(2编辑  收藏  举报

导航