Search code examples
delphifiremonkeydelphi-10.2-tokyo

MakeScreenshot for dynamically created control


I need to dynamically draw created control to bitmap.

But it does not work, it does not draw anything.

procedure TForm2.Button1Click(Sender: TObject);
var
  cb: TCheckBox;
  BMP: TBitmap;
begin
  BMP:= nil;

  cb:= TCheckBox.Create(nil);
  try
    cb.IsChecked:= true;
    cb.Repaint;
    BMP:= cb.MakeScreenshot;
    BMP.SaveToFile('C:\bmp.bmp');
  finally
    FreeAndNil(cb);
    FreeAndNil(BMP);
  end;
end;

I have tried also directly PaintTo - but the same effect. I have tried also setting parent but this is still not enough.

If i do same for control placed by hand on the form it is working, but dynamically created not.

How to do this. This control should not be visible anywhere i need to paint it only and free it.


Solution

  • Two issues. First, you do need the control to be parented for it to be paintable.

    Second, you're saving as a BMP which does not support the transparency used in FMX to generate the screenshot (and is platform specific besides). Save it as a PNG instead.

    procedure TForm1.FormCreate(Sender: TObject);
    var
      cb: TCheckBox;
      BMP: TBitmap;
    begin
      BMP:= nil;
      cb:= TCheckBox.Create(nil);
      try
        cb.Parent := self;
        cb.Text := 'testing';      
        cb.IsChecked:= true;
        bmp := cb.MakeScreenshot;
        BMP.SaveToFile('C:\bmp.png');
      finally
        cb.Free;
        BMP.Free;
      end;
    end;