Re: Drawing on Delphi TPaintBox

Posted by DelphiLand Team on December 28, 2005

In Reply to: Drawing on TPaintBox posted by Diane Channers

: I thought that a Delphi TPaintBox is to be used to draw custom images to a form, unlike TImage that displays an image that is stored in a file. So if I want to use Canvas.Rectangle and so on... use a PaintBox component.
: That works, but the problem is that I have to redraw everything if the window has been covered by another window. Is there a better component that "remembers" what I have drawn? 

Use an Image component instead of a PaintBox.

Like with a TPaintBox, you can draw items on the canvas of a TImage control. But a TImage will refresh itself when necessary, the image will be redrawn without your help if the image is moved or minimized or has other forms popup over it. This is not the case with a TPaintBox: it's the programmer's job to make sure that it knows how to "repaint" itself.

You can test this as follows in a project that lets you compare TPaintBox and TImage. When you click Button1, a blue rectangle is drawn in both controls. Run the application, minimize its window and restore it by clicking its button on the taskbar, and see what happened :)

procedure TForm1.Button1Click(Sender: TObject);
  with PaintBox1.Canvas do begin
    Brush.Style := bsSolid;
    Brush.Color := clBlue;
    Rectangle(0, 0, PaintBox1.Width, PaintBox1.Height);
  with Image1.Canvas do begin
    // Note: Canvas is only available if the Picture property represents a TBitmap object.
    // When Picture represents another type of graphic image, this gives an error. 
    Brush.Style := bsSolid;
    Brush.Color := clBlue;
    Rectangle(0, 0, Image1.Width, Image1.Height);

Related Articles and Replies