2010. június 29., kedd

How to do scaling while keeping the aspect ratio


Problem/Question/Abstract:

Currently I am using a whole bunch of if..then statements to compare the width and height of two rectangles and determine the scaling factor by dividing the original rect size (width or height) by the second rectangle size. If the second is smaller than the first, the scaling factor is 1. There must be a better way and I'm thinking of StretchDIBits(). Remember, I am trying to reduce the rectangle size while keeping the aspect ratio.

Answer:

Even using StretchDIBits, you have to calculate the scaling factor.


var
  XScale: Single;
  YScale: Single;
  Scale: Single;
begin
  XScale := 1.0;
  YScale := 1.0;
  if TargetWidth < SourceWidth then
    XScale := TargetWidth / SourceWidth;
  if TargetHeight < SourceHeight then
    YScale := TargetHeight / SourceHeight;
  Scale := XScale;
  if YScale < Scale then
    Scale := YScale;
end;


Now use Scale as your scaling factor.

Nincsenek megjegyzések:

Megjegyzés küldése