BGRABitmap tutorial 3

From Lazarus wiki
Revision as of 15:13, 12 March 2011 by Circular (talk | contribs) (→‎Create a new project: wiki BGRABitmap)
Jump to navigationJump to search

This tutorial shows you how to draw on a bitmap with the mouse.

Create a new project

Create a new project and add a reference to BGRABitmap, the same way as in the first tutorial.

Create a new image

Add a private variable to the main form to store the image : <delphi> TForm1 = class(TForm)

 private
   { private declarations }
   image: TBGRABitmap;
 public
   { public declarations }
 end; </delphi>

Create the image when the form is created. To do this, double-click on the form, a procedure should appear in the code editor. Add the create instruction : <delphi>procedure TForm1.FormCreate(Sender: TObject); begin

 image := TBGRABitmap.Create(640,480,BGRAWhite);  //create a 640x480 image

end; </delphi>

Draw the bitmap

Add an OnPaint handler. To do this, select the main form, then go to the object inspector, in the event tab, and double-click on the OnPaint line. Then, add the drawing code : <delphi>procedure TForm1.FormPaint(Sender: TObject); begin

 PaintImage;

end; </delphi>

Add the PaintImage procedure : <delphi>procedure TForm1.PaintImage; begin

 image.Draw(Canvas,0,0,True);

end; </delphi>

After writing this, put the cursor on PaintImage and press Ctrl-Shift-C to add the declaration to the interface.

Handle mouse

With the object inspector, add handlers for MouseDown and MouseMove events : <delphi>procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;

 Shift: TShiftState; X, Y: Integer);

begin

 if Button = mbLeft then DrawBrush(X,Y);

end;

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,

 Y: Integer);

begin

 if ssLeft in Shift then DrawBrush(X,Y);

end;</delphi>

Add the DrawBrush procedure : <delphi>procedure TForm1.DrawBrush(X, Y: Integer); const radius = 5; begin

 image.GradientFill(X-radius,Y-radius, X+radius,Y+radius,
   BGRABlack,BGRAPixelTransparent, gtRadial,
   PointF(X,Y), PointF(X+5,Y), dmDrawWithTransparency);
 PaintImage;

end;</delphi>

This procedure draws as radial gradient (gtRadial) :

  • the bounding rectangle is (X-radius,Y-radius, X+radius,Y+radius).
  • the center is black, the border is transparent
  • the center is at (X,Y) and the border at (X+5,Y)

Run the program

You should be able to draw on the form.

Previous tutorial