tags:

views:

265

answers:

3

How can I make my program load an image and make it the background for a form? I need the exact code for it. I've looked all over the internet and the only things I've found are various tweaks and fixes to make backgrounds work as intended in special circumstances. I've also tried some Delphi books I have and I can't find it anywhere.

+2  A: 
  1. Put a TImageon your form. Make sure it's behind all other controls on the form. You can right-click it and choose the "send to back" menu option.

  2. Load a graphic.

    var
      img: TBitmap;
    begin
      img := TBitmap.Create;
      try
        img.LoadFromFile('S:\background.bmp');
    
  3. Assign it to the image control.

        Image1.Picture := img;
    
  4. Clean up.

      finally
        img.Free;
      end;
    end;
    

You can also combine the last three steps to load the graphic and put it in the image control all at once. Thanks to Jon for the suggestion.

Image1.Picture.LoadFromFile('B:\background.bmp');

See also: How to add background images to Delphi forms

Rob Kennedy
I would love some feedback explaining what wasn't useful about this answer. Were there factual errors that I can correct, or is it fundamentally an unworkable solution?
Rob Kennedy
Why not load the image directly by the TImage control? That way you'd be able to use any image format that was loaded into TPicture (jpg, gif, etc..)
Jon Benedicto
Because I can't remember whether the Picture property is nil at first, and I can't remember whether TPicture knows how to load images by itself. Neither are problems, apparently. Thanks for the ideas.
Rob Kennedy
A: 

I believe it's done by overriding the default behaviour for the WM_ERASEBACKGROUND message. Have a look here http://www.google.be/search?rlz=1C1GGLS%5FnlBE291BE303&sourceid=chrome&ie=UTF-8&q=delphi+wmerasebackground+background+image (perhaps there's an example here http://www.google.com/codesearch?hl=nl&lr=&q=wmerasebackground+bitmap+lang%3Apascal&sbtn=Zoeken )

Stijn Sanders
A: 

What I would do is use the forms OnPaint event, get the canvas (Form1.Canvas), and then use the Draw method (which takes an image) to draw the image you want. Something like the following:

procedure TForm1.FormPaint(Sender: TObject);
var
mypic: TBitMap;
begin
mypic := TBitMap.Create;
try
mypic.LoadFromFile('cant.bmp');
Form1.Canvas.Draw(0, 0, mypic);
finally
FreeAndNil(mypic);
end;
end;

Note that this could be extremely slow.

Tom
You mention it as a note, but it really isn't a good idea to load a file in the paint event. Also, you should probably call the inherited `Paint` implementation.
Smasher
true. what would be better would be to load the image on the oncreate or onshow, then save it for re-use so it's not always re-loading when repainting. Also, frequent updates to the application will slow this down as well.
Tom