Dynamically Positioning the Control (C++ Builder)

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.

void __fastcall TForm1::LoadLeadClick(TObject *Sender)
{
   /* Declare variables used for preserving aspect ratios. */
   int HeightFactor, WidthFactor, HeightAllowed, WidthAllowed;
   AnsiString ImageFile;
   /* 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 = Lead1->InfoHeight;
   WidthFactor = Lead1->InfoWidth;
   HeightAllowed = (ClientHeight * 3) / 4;
   WidthAllowed = (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)
   {
      Lead1->Left = ClientWidth / 8;
      Lead1->Width = WidthAllowed;
      Lead1->Height = (Lead1->Width * HeightFactor) / WidthFactor;
      Lead1->Top = (ClientHeight - Lead1->Height) / 2;
   }
   else
   {
      Lead1->Top = ClientHeight / 8;
      Lead1->Height = HeightAllowed;
      Lead1->Width = (Lead1->Height * WidthFactor) / HeightFactor;
      Lead1->Left = (ClientWidth - Lead1->Width) / 2;
   }
   /* 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();
}

3.

Run your program to test it.