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