C# 计算图片最大缩放宽高的函数
/// <summary>
/// 计算同比缩放的值
/// </summary>
/// <param name="oW">原宽</param>
/// <param name="oH">原高</param>
/// <param name="w">目标宽</param>
/// <param name="h">目标高</param>
/// <param name="mode">HW(指定高宽缩放(可能变形)),W(指定宽,高按比例),H(指定高,宽按比例),MaxHW(最大宽高比例缩放,比如原100*50->50*30,则结果是50*25)</param>
/// <returns></returns>
public static WidthHeight TBScale(double oW,double oH,double w,double h,string mode= "W")
{
WidthHeight wh = new WidthHeight();
double ow = wh.width = oW;
double oh = wh.height = oH;
switch (mode)
{
case "HW": //指定高宽缩放(可能变形)
wh.width = (int)w;
wh.height = (int)h;
break;
case "W": //指定宽,高按比例
wh.height = oH * w / oW;
break;
case "H": //指定高,宽按比例
wh.width = oW * h / oH;
break;
case "Cut": //指定高宽裁减(不变形)
if ((double)oW / (double)oH > (double)wh.width / (double)wh.height)
{
oh = oH;
ow = oH * wh.width / wh.height;
}
else
{
ow = oW;
oh = oW * h / wh.width;
}
break;
case "MaxHW"://最大宽高比例缩放,比如原100*50->50*30,则结果是50*25
var rmaxhw_d1w = oW * 1.0 / w;
var rmaxhw_d2h = oH * 1.0 / h;
if (rmaxhw_d1w > rmaxhw_d2h)
{
if (rmaxhw_d1w <= 1)
{
wh.width = oW; h = oH;
goto case "HW";
}
wh.width = w;
goto case "W";
}
if (rmaxhw_d2h <= 1)
{
wh.width = oW; h = oH;
goto case "HW";
}
wh.height = h;
goto case "H";
default:
break;
}
wh.width = (int)wh.width;
wh.height = (int)wh.height;
return wh;
}
}
/// <summary>
/// 宽高类
/// </summary>
public class WidthHeight
{
/// <summary>
/// 宽
/// </summary>
public double width { get; set; }
/// <summary>
/// 高
/// </summary>
public double height { get; set; }
}
本文来自博客园,作者:jevan,转载请注明原文链接:https://www.cnblogs.com/DoNetCShap/p/14894781.html

浙公网安备 33010602011771号