BGRABitmap tutorial 4

From Lazarus wiki
Revision as of 15:29, 12 March 2011 by Circular (talk | contribs) (created)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

This tutorial shows you how to access directly to pixels.

Create a new project

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

Add a painting handler

With the object inspector, add an OnPaint handler and write : <delphi>procedure TForm1.FormPaint(Sender: TObject); var x,y: integer;

   p: PBGRAPixel;
   image: TBGRABitmap;

begin

 image := TBGRABitmap.Create(ClientWidth,ClientHeight);
 for y := 0 to image.Height-1 do
 begin
   p := image.Scanline[y];
   for x := 0 to image.Width-1 do
   begin
     p^.red := x*256 div image.Width;
     p^.green := y*256 div image.Height;
     p^.blue := 0;
     p^.alpha := 255;
     inc(p);
   end;
 end;
 image.Draw(Canvas,0,0,True);
 image.free;

end;</delphi>

This procedure creates a bitmap of the same size as the available client space. Then the loops access directly to pixel data to render a bidimensional gradient. Finally the image is drawn and freed.

To access to bitmap data, you can either use Data, if you do not mind the line order, or Scanline to access to a specific line. Within a line, pixels are ordered from left to right. Each component is defined. For example : <delphi>p^.red := x*256 div image.Width;</delphi> Defines a red component varying from 0 to 255 from left to right. The maximum value image.Width is never reached by x, so the red component never reach 256.

Run the program

You should see a form with a gradient where corners are black, red, yellow and green. When you resize the form, the gradient is resized accordingly.

Previous tutorial (drawing with the mouse)