views:

58

answers:

1

Hello everybody,

I'm having problems resizing a TPaintBox and drawing on it:

On my Form (named FMain) I dropped a TPaintBox (named DisplayImage), which I am trying to resize as the Form is resized.

To do that I wrote an OnResize() method for FMain (I confirmed that it's being called correctly) in which I try to resize the DisplayImage:

procedure TFMain.FormResize(Sender: TObject);
begin
   DisplayImage.Width := FMain.ClientWidth;
   DisplayImage.Height := FMain.ClientHeight;

   DisplayImage.Canvas.Brush.Color := clGreen;
   DisplayImage.Canvas.Brush.Style := bsSolid;
   DisplayImage.Canvas.Rectangle(0, 0, DisplayImage.Width, DisplayImage.Height);
end;

IMHO the last code should draw a full-image green rectangle over the complete image, making it effectively always green. Instead I get a grey image (just like the standard bg-color of Delphi) and every once in a while during resize for a split second the green image flashes up.

What am I missing, is there some hidden component I need to update after resizing?

Thank you in advance,

BliZZarD

+6  A: 

First of all, instead of doing

DisplayImage.Width := FMain.ClientWidth;
DisplayImage.Height := FMain.ClientHeight;

on each resize, simply set Align := alClient of the paint box.

Secondly, to draw to the paint box, use the OnPaint event of the paint box:

procedure TFMain.DisplayImagePaint(Sender: TObject);
begin
   DisplayImage.Canvas.Brush.Color := clGreen;
   DisplayImage.Canvas.Brush.Style := bsSolid;
   DisplayImage.Canvas.Rectangle(0, 0, DisplayImage.Width, DisplayImage.Height)
end;
Andreas Rejbrand
Thanks, worked like a charm :) But nevertheless it should be possible to draw on the Canvas, or does the OnPaint Event override my Drawing?
ThE_-_BliZZarD
You *are* drawing to the canvas. You do not *need* to do it `OnPaint` (even if that is a very good idea) -- you could do it on a `Button1Click` or something similar. However, form resize is a rather delicate time to do painting on. There might be a `WM_ERASEBKGND` or similar that undoes your painting.
Andreas Rejbrand
@ThE - (In addition to Andreas' comment) Think of it this way: OnPaint gets called whenever the PaintBox needs painting, but if you don't draw in OnPaint, your drawing will be erased f.i. when you bring another window in front of your form. There's an example on the documentation which shows the difference: http://docwiki.embarcadero.com/CodeSamples/en/OnPaint_%28Delphi%29
Sertac Akyuz