How to draw on the entire area of a resized TImage in Delphi?

PhiS picture PhiS · Oct 20, 2009 · Viewed 7.1k times · Source

I've narrowed a problem I have drawing on TImage.Canvas in Delphi 2009 down to the following reproducible case:

Given: a form, a TImage, TLabel and TButton on it. The TImage is anchored to all four edges so that resizing the form will resize the TImage. What I want to be able to do is draw on the maximal area of Image1 available to me after resizing. So in my test case I have the following code in my the Button's OnClick handler:


procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption:= IntToStr (Image1.Width)+' x '+IntToStr(Image1.Height);
  Image1.Canvas.Pen.Color:= 0;
  Image1.Canvas.Rectangle(0,0,Image1.Width, Image1.Height);
end;
You'll see that if the form is resized, Image1.Width and .Height change as expected, however the rectangle that is drawn if the resized form is larger than the original one, will be incomplete, only drawing on the same area that was there previously.

How do I get it do use the entire resized area?

For what it's worth, in my original problem I had played with Image1.Stretch, which allows me to use more of the area upon resizing but will result in my drawings being distorted (not desired). If I also use Image1.Proportional, then it's better but I still can't use the full area available. Image1.AutoSize doesn't seem to be doing anything useful to me either.

Any help appreciated.

Answer

Svein Bringsli picture Svein Bringsli · Oct 20, 2009

Add an OnResize-event to your form:

procedure TForm1.FormResize(Sender: TObject);
begin
  Image1.Picture.Bitmap.Width := Image1.Width;
  Image1.Picture.Bitmap.Height := Image1.Height;
end;

Also, if you are using the component to draw on, rather than displaying images from file etc, consider using the TPaintBox rather than TImage.