Restoring a Drawing

Introduction

If you draw on a canvas using the Mouse events, when the form looses focus, it also looses the image that was drawn. The only way you can keep your drawing is if you draw using the OnPaint event. This has to do with the operating system, not the VCL and you can get it regardless of the programming environment you are using.

This exercise shows how to restore that drawing when the form regains focus.

  1. Start Borland Delphi with the startup form.
  2. On the form, place a PaintBox control.
  3. In the declaration section of the form, you will need a Boolean variable that keeps track whether the user is drawing. You will also need a point variable that finds out the starting point of a drawing
    To implement the necessary behavior, you will need to initialize the DrawingBoard bitmap variable to occupy the PaintBox control. Then you will use the OnMouseDown, OnMouseUp, and OnPaint events of the PaintBox to do your thing.
    Here is the complete file
     
    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
      ExtCtrls;
    
    type
      TForm1 = class(TForm)
        PaintBox1: TPaintBox;
        procedure FormCreate(Sender: TObject);
        procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
          Shift: TShiftState; X, Y: Integer);
        procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
          Shift: TShiftState; X, Y: Integer);
        procedure PaintBox1Paint(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    var
      Form1: TForm1;
      DrawingBoard: TBitmap;
      IsDrawing: Boolean;
      StartX, StartY: Integer;
    
    implementation
    
    {$R *.DFM}
    
    procedure TForm1.FormCreate(Sender: TObject);
    begin
        DrawingBoard := TBitmap.Create;
        DrawingBoard.Width := PaintBox1.Width;
        DrawingBoard.Height := PaintBox1.Height;
    end;
    
    procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    begin
         IsDrawing := True;
        StartX := X;
        StartY := Y;
    end;
    
    procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    begin
         if IsDrawing then
         begin
            DrawingBoard.Canvas.Rectangle(StartX, StartY, X, Y);
            PaintBox1.Canvas.Draw(0, 0, DrawingBoard);
            IsDrawing := False;
         end;
    end;
    
    procedure TForm1.PaintBox1Paint(Sender: TObject);
    begin
         PaintBox1.Canvas.Draw(0, 0, DrawingBoard);
    end;
    
    end.
  4. Test the application

 

 

Copyright © 2004 FunctionX, Inc.