如何调整按钮大小以适合Delphi FireMonkey中的文本?

时间:2013-08-25 14:56:57

标签: delphi button text firemonkey delphi-xe4

我希望按钮大小(宽度和高度)尽可能小,但我希望它适合文本。任何代码示例? Delphi XE4 FireMonkey移动应用程序。

2 个答案:

答案 0 :(得分:9)

FireMonkey使用TTextLayout类通过方法呈现文本。
我们可以通过类助手访问这些方法,然后根据布局提供的信息更改按钮大小。

uses FMX.TextLayout;

type
  TextHelper = class helper for TText
     function getLayout : TTextLayout;
  end;

function TextHelper.getLayout;
begin
  result := Self.fLayout;
end;

procedure ButtonAutoSize(Button : TButton);
var
  bCaption : TText;
  m : TBounds;
begin
  bCaption := TText(Button.FindStyleResource('text',false));
  bCaption.HorzTextAlign := TTextAlign.taLeading;
  bCaption.VertTextAlign := TTextAlign.taLeading;
  m := bCaption.Margins;
  Button.Width  := bCaption.getLayout.Width  + m.Left + m.Right;
  Button.Height := bCaption.getLayout.Height + m.Top  + m.Bottom;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
   ButtonAutoSize(Sender as TButton);
end;

更新

这是一个更加面向未来的解决方案,不需要公开私有类字段。

uses FMX.Objects;

procedure ButtonAutoSizeEx(Button: TButton);
var
  Bitmap: TBitmap;
  Margins: TBounds;
  Width, Height: Single;
begin
  Bitmap := TBitmap.Create;
  Bitmap.Canvas.Font.Assign(Button.TextSettings.Font);
  Width := Bitmap.Canvas.TextWidth(Button.Text);
  Height := Bitmap.Canvas.TextHeight(Button.Text);
  Margins := (Button.FindStyleResource('text', false) as TText).Margins;
  Button.TextSettings.HorzAlign := TTextAlign.Leading;
  Button.Width := Width + Margins.Left + Margins.Right;
  Button.Height := Height + Margins.Top + Margins.Bottom;
end;

此示例省略了任何自动换行或字符修剪。

答案 1 :(得分:0)

基于@Peter的答案,但不需要创建位图:

//...

type
    TButtonHelper = class helper for TButton
        procedure FitToText(AOnlyWidth: Boolean = False);
    end;

implementation

//...

// Adapt button size to text.
// This code does not account for word wrapping or character trimming.
procedure TButtonHelper.FitToText(AOnlyWidth: Boolean = False);
var
    Margins: TBounds;
    TextWidth, TextHeight: Single;
    Obj: TFmxObject;
const
    CLONE_NO = False;
begin
    Obj := FindStyleResource('text', CLONE_NO);
    if Obj is TText then    //from Stackoverflow comments: Some time FindStyleResource returns nil making the app crash
    begin
        Margins := (Obj as TText).Margins;
        TextWidth := Canvas.TextWidth(Text);
        if not AOnlyWidth then
          TextHeight := Canvas.TextHeight(Text);
        TextSettings.HorzAlign := TTextAlign.taLeading;    //works in XE4
        //later FMX-Versions ?: TextSettings.HorzAlign := TTextAlign.Leading;
        Width := TextWidth + Margins.Left + Margins.Right;
        if not AOnlyWidth then
          Height := TextHeight + Margins.Top + Margins.Bottom;
    end;
end;