Pages

Tuesday 16 October 2012

How to set background image and color at runtime in Delphi XE2?

Sometimes we need to change the background image and background color of our delphi
from at runtime. In this article, I have tried to cover this topic.

I have stored 2 images in a folder 'Images'. I have stored the path and name of the image in a table and also the background color of the form (like clSkyBlue, clOlive). I will just pick the
path / name of the image and the background color at runtime from database and assign it to the delphi form.

Note: Background image occupies half height of the delphi form and rest background color is visible.

I will have to create 2 variables like:

FormImage : TImage;
FormPicture : TPicture;

Now I will use FormShow procedure to load image and background color at runtime.

procedure TMyClass.FormShow(Sender: TObject);
var
  ImagePath, BackColor: string;
begin
  try
     //ImagePath := Fetch from database and assign to it.
     //BackColor := Fetch from database and assign to it.
     FormPicture := TPicture.Create;
     FormPicture .LoadFromFile('.\Images\' + ImagePath);
     FormImage.Picture.Assign(FormPicture);
     myForm.Color := StringToColor(BackColor);
  except
    on E : Exception do
    begin
      ShowMessage('Some error occured in procedure FormShow: ' + E.Message);
    end;
  end;
end;

Explanation

First of all, create constructor of TPicture.
Then, use LoadFromFile to load the image to TPicture object.
Then, assign that TPicture to TImage object.
Then, assign back ground color to the delphi form.
 

No comments:

Post a Comment