Dynamically Positioning the Control (Delphi)
Take the following steps to dynamically scale and position the LEAD control when loading an image. This example scales the control to use most of the form's area while preserving the image's aspect ratio.
1. |
Start with the project that you created in Loading and Displaying an Image. |
2. |
Modify the LeadLoad button's click procedure so that it appears as follows. For a general explanation of how images are positioned and scaled, refer to Displaying an Image. |
procedure TForm1.LeadLoadClick(Sender: TObject);
var
{ Declare variables used for preserving aspect ratios. }
HeightFactor, WidthFactor, HeightAllowed, WidthAllowed: Integer;
ImageFile: String;
begin
{ This hard-coded path name may be different on your system. }
ImageFile := 'c:\lead\images\image1.cmp';
{ Get information about the image. }
Lead1.GetFileInfo(ImageFile, 0);
{ Set the variables used for preserving the aspect ratio.
Allow for a border of 1/8 of the form size. }
HeightFactor := round(Lead1.InfoHeight);
WidthFactor := round(Lead1.InfoWidth);
HeightAllowed := round(ClientHeight * 3/4);
WidthAllowed := round(ClientWidth * 3/4);
{ Center the LEAD control on the form, preserving the aspect ratio.
Check to see if using the maximum width will make the image too tall.
Set the dimensions based on the result. }
If ((WidthAllowed * HeightFactor) / WidthFactor) < HeightAllowed Then
begin
Lead1.Left := round(ClientWidth / 8);
Lead1.Width := WidthAllowed;
Lead1.Height := round((Lead1.Width * HeightFactor) / WidthFactor);
Lead1.Top := round((ClientHeight - Lead1.Height) / 2);
end
Else
begin
Lead1.Top := round(ClientHeight / 8);
Lead1.Height := HeightAllowed;
Lead1.Width := round((Lead1.Height * WidthFactor) / HeightFactor);
Lead1.Left := round((ClientWidth - Lead1.Width) / 2);
End;
{ Set the automated behavior so that we control the display size. }
Lead1.AutoSetRects := False;
Lead1.AutoRepaint := True;
Lead1.AutoScroll := False;
{ Set the image display size to match the LEAD control }
Lead1.SetSrcRect(0, 0, Lead1.InfoWidth, Lead1.InfoHeight);
Lead1.SetSrcClipRect(0, 0, Lead1.InfoWidth, Lead1.InfoHeight);
Lead1.SetDstRect(0, 0, Lead1.ClientWidth, Lead1.ClientHeight);
Lead1.SetDstClipRect(0, 0, Lead1.ClientWidth, Lead1.ClientHeight);
{ Load the bitmap. }
Lead1.Load(ImageFile, 0, 0, 1 );
Lead1.ForceRepaint;
end;
3. |
Run your program to test it. |