Run your own MMO
Run your own Strategy MMO! Easy to customize, addictive, and great for building a community of regular visitors!

 

Rescaling

In Category Geometry
Article published 23/11/2009 10:51:41pm
 
RescalingRescaling

A quick and painless method to rescale a given set of dimensions to find a best fit size within a new set of dimensions, while retaining apect ratio. Perfect for rescaling images or sprites, and best of all just a few short lines of code!


Rescaling dimensions whilst retaining the aspect ratio can be very useful when manipulating images on-the-fly, or automating image manipulation processes. To rescale a set of dimensions whilst retaining the aspect ratio we will need the following information:
  • The dimensions (OldW, OldH) of the origional object
  • The set of dimensions (MaxW, MaxH) that the old dimensions will be scaled to fit into
And our output (NewW, NewH) which will contain the newly scaled set of dimensions. Three lines of code will achieve this for us;
factor = ( (OldW/MaxW) > (OldH/MaxH) ? (MaxW/OldW) : (MaxH/OldH) );
NewW = floor( OldW*factor );
NewH = floor( OldH*factor );
The factor simply checks to see whether the old width fits into the maximum width more times than the old height fits into the new height, and then calculates the number of times the old dimension must be multiplied to fit into the new dimension. This factor of multiplication is then applied to both the old width and height, and the results rounded down to the nearest whole number (floor).
 
A quick example in Javascript would work as follows:
function Rescale200x200(image_w, image_h) {
  max_w = 200;
  max_h = 200;
 
  factor = ((image_w/max_w)>(image_h/max_h)?(max_w/image_w):(max_h/image_h));
 
  new_w = Math.floor(image_w*factor);
  new_h = Math.floor(image_h*factor);
 
  alert("Origional dimensions: "+image_w+" x "+image_h+
    "\nMaximum dimensions: "+max_w+" x "+max_h+
    "\nRescale result: "+new_w+" x "+new_h);
 
  return;
}