C#不改变图像长宽比例调整图像大小方式
作者:hyq106
文章介绍了在UI显示图片时,当容器大小固定而图片尺寸大于容器时,可以通过编码计算长宽来重绘图像,以确保图像的长宽比例不变,C#代码示例展示了如何在Winform前端实现这一功能
C#不改变图像长宽比例调整图像大小
在UI显示图片时,如果容器大小固定,而图片尺寸大于容器,那显示图片时会显示不全。
有些容器(例如PictureBox)本身可以通过设置属性来改变图像大小,让图像大小自动适应容器,但这不能保证图像的长宽比例不变。
这时,我们可以通过编码计算长宽来重绘图像。
C#代码
如下:
/// <summary> /// 根据容器(如PictureBox)长宽的限制,在不改变图像比例的情况下,调整图像大小 /// author:huangyq1984@qq.com /// </summary> /// <param name="maxWidth">容器宽</param> /// <param name="maxHeight">容器高</param> /// <param name="srcImg">原图</param> /// <param name="backColor">空白处的背景色</param> /// <returns></returns> public static Image GetImageToFitContainer(int maxWidth,int maxHeight, Image srcImg, Color backColor) { if (srcImg == null) return null; float Scale; int iw, ih; //计算原图的长宽比例 Scale = (float)srcImg.Height / (float)srcImg.Width; iw = srcImg.Width; ih = srcImg.Height; //如果原图长宽都不大于容器长和宽,则不需要调整大小 if (srcImg.Width <= maxWidth && srcImg.Height <= maxHeight) { iw = srcImg.Width; ih = srcImg.Height; } //如果原图宽大于容器宽,且原图高不大于容器高,则调整后的图像宽就是容器宽,图像高需要根据长宽比例来计算 else if (srcImg.Width > maxWidth && srcImg.Height <= maxHeight) { iw = maxWidth; ih = (int)(Scale * iw); } //如果原图高大于容器高,且原图宽不大于容器宽,则调整后的图像高就是容器高,图像宽需要根据长宽比例来计算 else if (srcImg.Width <= maxWidth && srcImg.Height > maxHeight) { ih = maxHeight; iw = (int)(ih / Scale); } //如果原图高和宽都大于容器高和宽,则调整后的图像高和图像宽都需要重新计算 else if (srcImg.Width > maxWidth && srcImg.Height > maxHeight) { iw = maxWidth; ih = (int)(Scale * iw); if (ih > maxHeight) { ih = maxHeight; iw = (int)(ih / Scale); } } //构建新的位图 Bitmap bmp = new Bitmap(iw, ih); Graphics g = Graphics.FromImage(bmp); //用背景色填充 g.Clear(backColor); //在位图上根据调整后的高和宽绘制原图 g.DrawImage(srcImg, 0, 0, iw, ih); //保存 System.IO.MemoryStream ms = new System.IO.MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); g.Dispose(); srcImg = (Image)bmp; return srcImg; }
C#Winform前端调用
如下:
Image srcImage = Image.FromFile(fileName); pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; pictureBox1.Image = GetImageToFitContainer(pictureBox1.Width,pictureBox1.Height,srcImage,Color.Transparent);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。