Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Form while keeping aspect ratio

I have a Window, in which i display a picture. I want the user to be able to resize this window, but keep it in the same aspect ratio than the image, so no big empty areas appear on the window.

What i tried is something like this in the OnResize event:

DragWidth := Width;
DragHeight := Height;

//Calculate corresponding size with aspect ratio
//...
//Calculated values are now in CalcWidth and CalcHeight

Width := CalcWidth;
Height := CalcHeight;

The Problem with this is, that the window flashes during the resize dragging between the original resize size and the calculated, since the OnResize event is afaik called after the resize is already done (and painted once).

Do you know any solution for having a smooth aspect-ratio resizing?

Thanks for any Help.

like image 677
Marks Avatar asked Jun 07 '11 13:06

Marks


1 Answers

Adding the following handler for the OnCanResize event seemed to work very well for me:

procedure TForm1.FormCanResize(Sender: TObject; var NewWidth,
  NewHeight: Integer; var Resize: Boolean);
var
  AspectRatio:double;
begin
  AspectRatio:=Height/Width;
  NewHeight:=round(AspectRatio*NewWidth);
end;

You may of course want to change the method for calculating NewHeight and NewWidth. The following method feels intuitively "right" when I try it on a blank form:

  NewHeight:=round(0.5*(NewHeight+AspectRatio*NewWidth));
  NewWidth:=round(NewHeight/AspectRatio);
like image 71
boileau Avatar answered Oct 06 '22 08:10

boileau