PresleyDias
PresleyDias

Reputation: 3711

Delphi 7, how to copy Paintbox content to a Tbitmap?

im working on delphi 7 and i want to how to copy/assign the content of a TpaintBox to a Tbitmap?

like this

 public
  { Public declarations }
   BitMap     : TBitmap;
 end;

i have a Tbitmap declared as public and i create it onFormCreate like this

      procedure TForm1.FormCreate(Sender: TObject);
      begin
      BitMap     := TBitMap.Create;
      end;

Then i draw somthing on the bitmap like this

      procedure TForm1.DrawOnPainBox;
        begin
         If BitMap.Width  <> PaintBox1.Width  then BitMap.Width  := PaintBox1.Width;
         If BitMap.Height <> PaintBox1.Height then BitMap.Height := PaintBox1.Height;
         BitMap.Canvas.Rectangle(0,0,random(PaintBox1.Width ),random(PaintBox1.Height));
         PaintBox1.Canvas.Draw(0,0,BitMap);
        end;

with PaintBox1.Canvas.Draw(0,0,BitMap); we can display what is there in Bitmap to a paintbox but what is the reverse way?

how to assign/copy content of a paintbox to a bitmap?

 `BitMap:=PaintBox1.Canvas.Brush.Bitmap;` 

this compiles but if i do this and again call the procedure TForm1.DrawOnPainBox; i get access Violation and the debugger show the bitmap and PaintBox1.Canvas.Brush.Bitmap even though some lines are drawn on the paintBox

enter image description here

enter image description here

Upvotes: 4

Views: 9098

Answers (2)

St&#233;phane79
St&#233;phane79

Reputation: 31

TBitmap.setsize has been introduced in Delphi 2006, you may be using an older version. Just replace Bitmap.SetSize (X, Y)

by

Bitmap.Width := X
Bitmap.Height := Y

it's slower (but it matters only if you use it in a loop), but you will compile the code

if this happens too often, declare a new unit BitmapSize.pas:

unit BitmapSize;

interface

uses
    graphics;

Type
    TBitmapSize = class (TBitmap)
    public
        procedure Setsize (X, Y : integer);
    end;



implementation

procedure TBitmapsize.Setsize(X, Y: integer);
begin
    Width := X;    // may need some more tests here (X > 0, Y > 0, ...)
    Height := Y;
end;

end.

then replace in declaration and creation of your bitmap TBitmap with TBitmapSize.

..
Var
  B : TBitmapSize;
..
  B := TBitmapSize.Create;

Upvotes: 2

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

To assign the contents of a TPaintBox (let's call it PaintBox1) to a TBitmap (Bitmap, say), you can do

Bitmap.Width := PaintBox1.Width;
Bitmap.Height := PaintBox1.Height;
BitBlt(Bitmap.Canvas.Handle,
  0,
  0,
  Bitmap.Width,
  Bitmap.Height,
  PaintBox1.Canvas.Handle,
  0,
  0,
  SRCCOPY);

Notice: In newer versions of Delphi, you can use Bitmap.SetSize instead of Bitmap.Width and Bitmap.Height.

Upvotes: 10

Related Questions