Delphi 7, how to copy paintbox contents to tbitmap?

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

like this

public { Public declarations } BitMap : TBitmap; end; 

I have a Tbitmap declared as open, and I create it onFormCreate like this

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

Then I draw somthing on a 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; 

using PaintBox1.Canvas.Draw(0,0,BitMap); we can display what is in Bitmap in paintbox, but what is the return path?

How to assign / copy the contents of a field for drawing to a bitmap?

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

this will compile, but if I do this and call procedure TForm1.DrawOnPainBox; I get access Violation , and the debugger displays bitmap and PaintBox1.Canvas.Brush.Bitmap , although some lines are drawn on paintBox

enter image description here

enter image description here

+4
source share
2 answers

To assign the contents of TPaintBox (call it PaintBox1 ) to 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); 

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

+10
source

TBitmap.setsize was introduced in Delphi 2006, you can use an older version. Just replace Bitmap.SetSize (X, Y)

by

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

it is slower (but this is important only if you use it in a loop), but you compile the code

If this happens too often, declare a new BitmapSize.pas block:

 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 the declaration and create the TBitmap bitbip using TBitmapSize.

 .. Var B : TBitmapSize; .. B := TBitmapSize.Create; 
+1
source

Source: https://habr.com/ru/post/1391804/


All Articles