Delphi 7,如何将Paintbox内容复制到Tbitmap?

Delphi 7,如何将Paintbox内容复制到Tbitmap?,delphi,delphi-7,draw,Delphi,Delphi 7,Draw,我正在使用delphi 7,我想知道如何将TpaintBox的内容复制/分配到Tbitmap 像这样 public { Public declarations } BitMap : TBitmap; end; 我有一个Tbitmap声明为public,我在formcreate上创建它,如下所示 procedure TForm1.FormCreate(Sender: TObject); begin BitMap := TBitMa

我正在使用delphi 7,我想知道如何将TpaintBox的内容复制/分配到Tbitmap

像这样

 public
  { Public declarations }
   BitMap     : TBitmap;
 end;
我有一个Tbitmap声明为public,我在formcreate上创建它,如下所示

      procedure TForm1.FormCreate(Sender: TObject);
      begin
      BitMap     := TBitMap.Create;
      end;
      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;
然后我在位图上画一些东西,像这样

      procedure TForm1.FormCreate(Sender: TObject);
      begin
      BitMap     := TBitMap.Create;
      end;
      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;
这会编译,但如果我这样做并再次调用
过程TForm1.DrawOnPainBox
我得到
访问冲突
,调试器显示
位图
PaintBox1.Canvas.Brush.bitmap
,即使在paintBox上画了一些线


要将
tpaitbox
(我们称之为
PaintBox1
)的内容分配给
TBitmap
位图
),可以执行以下操作

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

注意:在较新版本的Delphi中,您可以使用
Bitmap.SetSize
而不是
Bitmap.Width
Bitmap.Height

TBitmap.SetSize,您可能使用的是较旧版本。替换
Bitmap.SetSize(X,Y)

它的速度较慢(但只有在循环中使用它时才重要),但您将编译代码

如果这种情况太频繁,请声明一个新的单位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.
然后在位图TBitmap的声明和创建中替换为TBitmapSize

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

画笔的
位图
,不是实际的位图@AndreasRejbrand好的,那么如何获得实际的位图呢?嘿,上面写着
未声明的标识符:'SetSize'
@PresleyDias:不,我不这么认为。您一定做错了什么事。
procedure TForm1.Button1Click(发送者:TObject);开始位图。设置大小(PaintBox1.Width,PaintBox1.Height);BitBlt(Bitmap.Canvas.Handle,0,0,Bitmap.Width,Bitmap.Height,PaintBox1.Canvas.Handle,0,0,SRCCOPY);结束
对于这个im,我得到了
未声明的标识符:“SetSize”
@PresleyDias:你确定你已经声明了一个名为
Bitmap
的变量,类型为
TBitmap
?@PresleyDias:好的,我现在知道
SetSize
并不总是
TBitmap
(它可能不在Delphi7中——我使用的是Delphi 2009)。因此,只需执行
Bitmap.Width:=PaintBox1.Width;Bitmap.Height:=PaintBox1.Height