Saturday, May 9, 2009

Aspect Ratio

Algorithm to resize a graphic and maintain the aspect ratio:

isoScalar = Min((dstWidth / srcWidth), (dstHeight / srcHeight)) 
newWidth = isoScalar * srcWidth
newHeight = isoScalar * srcHeight

Here is a C# function:

/// <summary>///
Rescale the source size to fit inside the template size and maintain the aspect ratio
/// </summary>
Size Rescale(Size szeSource, Size szeTemplate)

  int newWidth = 0; 
 
int newHeight = 0; 
  try //handle possible divide by zero 
  {  
    float isoScalar = Math.Min(((float szeTemplate.Width / szeSource.Width), ((float)szeTemplate.Height / szeSource.Height)); 

    newWidth = (int)(isoScalar * szeSource.Width);  
    newHeight = (int)(isoScalar * szeSource.Height); 
  } 
  catch{}  

  return new Size(newWidth, newHeight);
}

No comments: