[英]Calculate Width and Height respecting Aspect Ratio for any given Max Width and Max Height
我被要求在尊重图片原始纵横比的同时将任何图片调整为其等效缩略图的大小。
到目前为止,我只通过了最大值就完成了这一点。 宽度,如下:
public static Size GetSizeAdjustedToAspectRatio(int sourceWidth, int sourceHeight, int dWidth, int dHeight)
{
bool isLandscape = sourceWidth > sourceHeight;
int fixedSize = dWidth;
double aspectRatio = (double)sourceWidth / (double)sourceHeight; ;
if (isLandscape)
return new Size(fixedSize, (int)((fixedSize / aspectRatio) + 0.5));
else
return new Size((int)((fixedSize * aspectRatio) + 0.5), fixedSize);
}
我尝试了几种计算它的方法,以便它接受任何给定的最大值。 高度和最大值宽度以保持最终结果图片的原始纵横比。
这里:
public static Size GetSizeAdjustedToAspectRatio(int sourceWidth, int sourceHeight, int dWidth, int dHeight) {
bool isLandscape = sourceWidth > sourceHeight;
int newHeight;
int newWidth;
if (isLandscape) {
newHeight = dWidth * sourceHeight / sourceWidth;
newWidth = dWidth;
}
else {
newWidth = dHeight * sourceWidth / sourceHeight;
newHeight = dHeight;
}
return new Size(newWidth, newHeight);
}
在横向中,您将缩略图宽度设置为目标框宽度,高度由三规则确定。 在纵向中,您将缩略图高度设置为目标框高度并计算宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.