[英]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.