0

我在创建组件时遇到问题。我想在这个图像的中心有一个图像和简单的标签。它必须是一个组件,因为我将根据代码动态创建它。这个怎么做?我不知道如何将两个组件合并为一个。

4

1 回答 1

1

如果您想将其实现为自己的组件,最快的方法可能是从 TImage 继承,这将提供图像所需的所有属性并覆盖 Paint 方法,访问祖先的画布,这不会在 Bitmap 上产生任何机会. 简短的示例不涉及 Stretch,您必须自己实现它。

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.

一个示例用法是:

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;
于 2014-04-14T08:36:09.010 回答