0

I have problem with creating a component. I want to have an image and simple label on the center of this image. It have to be a component because I will create it dynamically form the code. How to do this? I don't know how to merge two components into one.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michał Kwiecień
  • 2,734
  • 1
  • 20
  • 23

1 Answers1

1

If you want to implement it as an own Component the fastest way might be to inherit from TImage, which would offer all Properties needed for images and Override the Paint method, accessing the canvas of the ancestor, this will not make any chances on the Bitmap. The short example is not dealing with Stretch, you will have to implement it on your own.

unit CaptionImage;

interface

uses Windows, Classes, Controls, ExtCtrls, Graphics, PNGIMage, jpeg;

type
  // maybe we want to do some more action on the Canvas without manipulation the Bitmap
  TOnAfterpaintEvent = Procedure(Sender: TObject; Canvas: TCanvas) of object;

  TGraphicControl = Class(Controls.TGraphicControl) // make canvas accessable
  public
    Property Canvas;
  End;

  TCaptionImage = Class(ExtCtrls.TImage)
  private
    ICanvas: TCanvas;
    FOnAfterPaint: TOnAfterpaintEvent;
    function GetFont: TFont;
  published
  public
    procedure Paint; override;
  published
    Property OnAfterPaint: TOnAfterpaintEvent Read FOnAfterPaint Write FOnAfterPaint;
    Property Caption;
    Property Font: TFont read GetFont;
  End;

implementation

function TCaptionImage.GetFont: TFont;
begin
  Result := TGraphicControl(Self).Canvas.Font;
end;

procedure TCaptionImage.Paint;
var
  s: String;
  r: TRect;
begin
  inherited;
  r := ClientRect;
  s := Caption;
  ICanvas := TGraphicControl(Self).Canvas;
  ICanvas.Brush.Style := bsClear;
  ICanvas.Textrect(r, s, [tfVerticalCenter, tfCenter, tfSingleLine]);
  if Assigned(FOnAfterPaint) then
    FOnAfterPaint(Self, ICanvas);
end;

end.

an example usage would be:

procedure TForm5.Button1Click(Sender: TObject);
begin
   With TCaptionImage.Create(self) do
    begin
      Parent := self;
      AutoSize := true;
      Font.Color := clBlue;
      Font.Size := 20;
      Picture.LoadFromFile('C:\temp\Bild 1.png');
      Caption := 'Test';
    end;
end;
bummi
  • 27,123
  • 14
  • 62
  • 101