![](/img/trans.png)
[英]How center and size a div/img of unknown size/aspect ratio within a browser window
[英]How do I find a dimension of aspect ratio 4:3 which fits within a predetermined size?
這里的問題是我有一個x和y大小的顯示窗口,我需要在窗口內顯示一個沒有任何滾動的圖像,並保持4:3的寬高比。 我有以下代碼片段:
// Lock the current height, calculate new width of the canvas and scale the viewport.
// get width of the movie canvas
qreal width = canvas_->width();
// Find the height of the video
qreal height = (width/4.0) * 3;
// find original width and height for video to calculate scaling factor
qreal videoWidth = movieData_->GetWidth();
qreal videoHeight = movieData_->GetHeight();
// calculate scaling factor
qreal scaleFactorWidth = width/videoWidth;
qreal scaleFactorHeight = height/videoHeight;
當然,通過使用高度或寬度作為“錨點”,新圖像將以這種方式或其他方式引起滾動(假設原始圖像首先大於窗口)。 如何找到適合預定尺寸的寬高比4:3的尺寸?
編輯我需要傳遞x和y的比例因子來進行縮放
canvas_->scale(scaleFactorWidth, scaleFactorHeight);
只需取兩個計算值中的最小值:
scale = min(scaleFactorWidth, scaleFactorHeight)
或(如果你想要外套)
scale = max(scaleFactorWidth, scaleFactorHeight)
struct dimensions resize_to_fit_in(struct dimensions a, struct dimensions b) {
double wf, hf, f;
struct dimensions out;
wf = (double) b.w / a.w;
hf = (double) b.h / a.h;
if (wf > hf)
f = hf;
else
f = wf;
out.w = a.w * f;
out.h = a.h * f;
return out;
}
這是一個C版本,其中返回的尺寸將是尺寸'a',尺寸'b',而不會失去縱橫比。
找到兩個值寬度中的最大值w
和高度h
。 假設您的最大寬度x
高度為100 x
80.請注意,100/80 = 1.25。
情況1:如果w/h > 1.25
,則將w
除以100,得到原始大小與新大小的比率。 然后將h
乘以該比率。
情況2:否則,然后將h
除以80以獲得原始大小與新大小的比率。 然后將w
乘以該比率。
這是你問的ActionScript版本(在保持寬高比的同時調整大小)......不應該太難以移植到任何東西:
private static function resizeTo(dispObj:DisplayObject, width:Number, height:Number) : void
{
var ar:Number = width / height;
var dispObjAr:Number = dispObj.width/dispObj.height;
if (ar < dispObjAr)
{
dispObj.width = width;
dispObj.height = width / dispObjAr;
}
else
{
dispObj.height = height;
dispObj.width = height * dispObjAr;
}
return;
}
編輯:為了維持4:3,源圖像需要為4:3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.