0
0

More than 1 year has passed since last update.

アスペクト比を固定したまま画像のサイズをフレームに合わせる

Last updated at Posted at 2021-10-23

以下の図のように画像のアスペクト比を固定したままフレームにフィットさせたいことがよくあります.
その時にフレームサイズとイメージサイズを入力,フィットさせるときのイメージサイズを出力とするアルゴリズムのメモです.

Screenshot from 2021-10-24 02-08-36.png

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];
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0