Search code examples
delphieventscanvascomponentstimage

how to use Picture.LoadFromFile() in TcustomContol


I created a TSkinPanel derive from TcustomControl

it has a FGraphic: TPicture.

the FGraphic is drawn on the canvas of the TSkinPanel and works fine if you load and image from the TObject Inspector.

but i doesnt won'k work on loading image on runtime "Form1.SkinPanel1.Picture.LoadFromFile('skin.bmp');


Solution

  • You have to use the TPicture.OnChange event, eg:

    type
      TSkinPanel = class(TCustomControl)
      private
        FPicture: TPicture;
        procedure PictureChanged(Sender: TObject);
        procedure SetPicture(Value: TPicture);
      protected
        procedure Paint; override;
      public
        constructor Create(Owner: TComponent); override;
        destructor Destroy; override;
      published
        property Picture: TPicture read FPicture write SetPicture;
      end;
    
      constructor TSkinPanel.Create(Owner: TComponent);
      begin
        inherited;
        FPicture := TPicture.Create;
        FPicture.OnChange := PictureChanged;
      end;
    
      destructor TSkinPanel.Destroy;
      begin
        FPicture.Free;
        inherited;
      end;
    
      procedure TSkinPanel.PictureChanged(Sender: TObject);
      begin
        Invalidate;
      end;
    
      procedure TSkinPanel.SetPicture(Value: TPicture);
      begin
        FPicture.Assign(Value);
      end;
    
      procedure TSkinPanel.Paint;
      begin
        if (FPicture.Graphic <> nil) and (not FPicture.Graphic.Empty) then
        begin
          // use FPicture as needed...
        end;
      end;