Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CopyRect method in Delphi

Tags:

delphi

I'm loading an image from disk and want to copy (part of) it to a second TImage:

Image1.Picture.LoadFromFile(S);
with Image1.Picture.Bitmap do
  Image2.Canvas.CopyRect(Image2.Canvas.ClipRect, Canvas, Canvas.ClipRect);

Image2 just shows a white rectangle, and Image1 doesn't show the file from disk. If I remove the second statement Image1 does show the image. (Strangest thing: if I only comment out the CopyRect statement and leave the "with" line (empty statement) Image1 doesn't show either!)

How do I use CopyRect to copy part of an image?

edit
When I split the two statements into two separate actions (buttons) the following happens:

  1. Image loads and shows in Image1
  2. Image1 disappears(!), and Image2 shows a white rectangle.

BTW, I'm using Delphi 2009.

like image 232
stevenvh Avatar asked Dec 02 '11 17:12

stevenvh


1 Answers

TCanvas.CopyRect copies the rectangle by using StretchBlt. StretchBlt requires a bitmap. If you're loading any other graphic type to your image then its Picture.Bitmap is empty. In fact the bitmap gets created just when you refer to it: with Image1.Picture.Bitmap do.

You can use a temporary bitmap for the cause:

var
  Bmp: TBitmap;
begin
  Image1.Picture.LoadFromFile(S);

  Bmp := TBitmap.Create;
  try
    Bmp.Assign(Image1.Picture.Graphic);

    with Bmp do
      Image2.Canvas.CopyRect(Image2.Canvas.ClipRect, Canvas, Canvas.ClipRect);
  finally
    Bmp.Free;
  ..
like image 176
Sertac Akyuz Avatar answered Sep 22 '22 16:09

Sertac Akyuz