FMXTBitmapDataPixel (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example shows how to use the TBitmapData.GetPixel and TBitmapData.SetPixel methods. This sample draws and fills the rectangle on an image, pixel by pixel.

To build and test this example, create a Multi-Device Application - Delphi, then add the folowing objects to the form:

  • A TImage to display the TBitmap.
  • A TLabel to display the value of the TTrackBar.
  • A TTrackBar to control the amount of Red in relation to which the transparency of certain pixels changes.

Add the following code to the OnChange event handlers of the track bar.

Code

procedure TForm1.FormCreate(Sender: TObject);
begin
  MyBitmap := TBitmap.Create(0, 0);
  MyBitmap.Assign(Image1.Bitmap);
end;

Add the following code to the OnChange event handlers of the track bar.

Code

procedure TForm1.TrackBar1Change(Sender: TObject);
var
  MyBitmapCopy: TBitmap;
  X, Y: Integer;
  CurrentData,ModifiedData : TBitmapData;
  Color: TAlphaColor;
begin
  MyBitmapCopy := TBitmap.Create(0, 0);
  MyBitmapCopy.Assign(MyBitmap);
  Label1.Text := TrackBar1.Value.ToString();
  try
    // Changes the color of certain pixels.
    // This changes the transparency of the pixels that have the amount of Red.
    // lower then the curent value of the trackbar
    if (MyBitmap.Map(TMapAccess.Read, CurrentData) and (MyBitmapCopy.Map(TMapAccess.Write,ModifiedData))) then
    begin
      try
        for X := 0 to MyBitmap.Width - 1 do
          for Y := 0 to MyBitmap.Height - 1 do
          begin
               Color := CurrentData.GetPixel(X, Y);
            if (TAlphaColorRec(Color).R < Label1.Text.ToInteger) then
            begin
             //255 is the maximum value for a color channel
              TAlphaColorRec(Color).A := 255-Label1.Text.ToInteger;
              ModifiedData.SetPixel(X, Y, Color);
            end;
          end;
      finally
        MyBitmap.Unmap(CurrentData);
        MyBitmapCopy.Unmap(ModifiedData);
      end;
    end;
    Image1.Bitmap := MyBitmapCopy;
  finally
    MyBitmapCopy.Free;
  end;

end;

The result should look like the following image:

TBitmapDataPixel.png

Uses

See Also