以下の図のように画像のアスペクト比を固定したままフレームにフィットさせたいことがよくあります.
その時にフレームサイズとイメージサイズを入力,フィットさせるときのイメージサイズを出力とするアルゴリズムのメモです.
Input
入力はフレームのサイズとイメージのサイズで以下の様になります.
frame_w, frame_h, image_w, image_h
Output
出力は新しいイメージのサイズです.
new_image_w, new_image_h
アルゴリズム
フィットする画像サイズを取得する,JavaScriptの関数は以下のようになります.
fit_image.js
function fit_image(frame_w, frame_h, image_w, image_h) {
var new_image_w, new_image_h;
var as_f = frame_w / frame_h;
var as_i = image_w / image_h;
if (as_f >= as_i)
{
new_image_h = frame_h;
new_image_w = new_image_h * as_i;
}
else
{
new_image_w = frame_w;
new_image_h = frame_w * (1 / as_i);
}
return [new_image_w, new_image_h];
}