Author: Lou Adler
Web pages use tiled bitmaps to create backgrounds. Is it possible to do this in
Delphi?
Answer:
Before I learned how to do this, to create a background on a form, I'd drop a
TImage on my form, then set its Align property to alClient. For low-resolution
bitmaps, the pixelation that would occur at times was absolutely terrible! But with
the method that I'll show you here (Note: this is merely ONE way of doing it), you
can easily tile bitmaps on the surface of your form. The trick is in trapping the
WM_ERASEBKGND message in a handler, creating a bitmap at runtime, then writing a
quick bit of code in the OnPaint event handler. Let's go through the steps.
1. In the private section of your code place the following:
1 private
2 { Private declarations }
3 MyBitmap: TBitmap;
4
5 procedure WMEraseBkgnd(var m: TWMEraseBkgnd);
6 message WM_ERASEBKGND;
7
8 Notice the declaration of MyBitmap. We'll be creating an instance for it below. The
9 message handler for WM_ERASEBKGND looks like this:
10
11 procedure TBmpform.WMEraseBkgnd(var m: TWMEraseBkgnd);
12 begin
13 m.Result := LRESULT(False);
14 end;
2. Then, create the following code for the OnPaint event handler Note: In the
original article, the "x := x + MyBitmap.Width" is a bit inefficient in that
continuously accessing the Bitmap.Width or .Height properties can slow things down
- especially when you've got code in the OnPaint method. So what I did here was to
simply set a couple of variables to store the Width and Height property values of
the bitmap.
15 procedure TBmpForm.FormPaint(Sender: TObject);
16 var
17 x, y: Integer;
18 iBMWid, iBMHeight: Integer;
19 begin
20 iBMWid := MyBitmap.Width;
21 iBMHeight := MyBitmap.Height;
22 y := 0;
23 while y < Height do
24 begin
25 x := 0;
26 while x < Width do
27 begin
28 Canvas.Draw(x, y, MyBitmap);
29 x := x + iBMWid;
30 end;
31 y := y + iBMHeight;
32 end;
33 end;
3. Finally, create an instance of the bitmap you want to tile in the background in
the OnCreate event of your form:
34 procedure TForm1.FormCreate(Sender: TObject);
35 begin
36 Application.OnHint := ShowHint;
37 MyBitmap := TBitmap.Create;
38 MyBitmap.LoadFromFile('Brick4.bmp');
39 end;
40
41 4. Whoops, almost forgot! You need to destroy the bitmap when you exit!
42
43 procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
44 begin
45 Action := caFree;
46 bmpBackground.Free;
47 end;
Well, that's it. Don't you just love the quick and dirty ones?
|