Calculate aspect ratio based on width and height

For a project i’m working on i had the need to calculate the aspect ratio par (4:3, 16:9, etc.) based on the width and height entered.

Santiago Anglés once again helped me out. He pointed me to this wikipedia entry: Euclidean Algorithm that let me get the greatest common divisor very easily and with that the rest was simple

  1. private function getMCD(w:int, h:int):int{
  2. return ((h != 0) ? arguments.callee(h, w % h): w);
  3. }
  4. public function getAspectRatio(w:uint, h:uint):String{
  5. var mcd:Number = getMCD(w, h);
  6. return [(w / mcd), (h / mcd)].join(":");
  7. }

And here some tests:

  1. trace (getAspectRatio(320, 240)); // 4:3
  2. trace (getAspectRatio(540, 480)); // 9:8
  3. trace (getAspectRatio(550, 400)); // 11:8

Thanks Buddy!

—fernando


comments

Erik Porroa

alguien debe limpiar estos comentarios… eso que dice en chino no es muy bueno :P

Leave a comment