Moving bitmap pixels

delphi, delphi-xe

Solution

You can't easily move pixels, but you can make a copy.

var
  Source, Dest: TRect;
....
Source := Rect(0, 0, Bitmap.Width, Bitmap.Height);
Dest := Source;
Dest.Offset(X, Y);
Bitmap.Canvas.CopyRect(Dest, Bitmap.Canvas, Source);

What remains is to fill in the space with the colour of your choice which I am sure you can do easily enough with a couple of calls to `FillRect`.

However, I think that it would be simpler not to attempt this in-place. Instead I would create a new bitmap. Perhaps like this:

function CreateMovedImage(Bitmap: TBitmap; X, Y: Integer; BackColor: TColor): TBitmap;
var
  Source, Dest: TRect;
begin
  Source := Rect(0, 0, Bitmap.Width, Bitmap.Height);
  Dest := Source;
  Dest.Offset(X, Y);

  Result := TBitmap.Create;
  Try
    Result.SetSize(Bitmap.Width, Bitmap.Height);

    Result.Canvas.Brush.Style := bsSolid;
    Result.Canvas.Brush.Color := BackColor;
    Result.Canvas.FillRect(Source);

    Result.Canvas.CopyRect(Dest, Bitmap.Canvas, Source);
  Except
    Result.Free;
    raise;
  End;
end;

Problem

If I wanted to move / shift the pixels of a bitmap how could I do so? ``` procedure MovePixels(Bitmap: TBitmap; Horizontal, Vertical: Integer); begin { move the Bitmap pixels to new position } end; ``` Example: By calling `MovePixels(Image1.Picture.Bitmap, 20, 20)` for example would output like so: It would be useful to also specify / change the color of the canvas that is left showing after moving the pixels. So in this example that gray / brown color could be blue etc. I noticed there is `Bitmap.Canvas.Pixels` and `Bitmap.Canvas.MoveTo` properties, is this what I would need to do this? I really don't know and I bet it is so simple..

Original source