本文介绍了如何调整按钮大小以适合在Delphi FireMonkey文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按钮的大小(宽度和高度),以尽可能小,但我想它适合文本。任何code的例子吗?
德尔福XE4 FireMonkey Mobile应用程序。
I want button size (width and height) to be as small as possible, but I want it to fit the text. Any code example?Delphi XE4 FireMonkey Mobile Application.
推荐答案
FireMonkey呈现通过使用的类。结果我们可以基于布局提供的信息,通过类的辅助访问此方法,然后更改按钮的大小。
FireMonkey renders text via methods using TTextLayout class.
We can access this methods via a class helper and then change the buttons size based on the information provided by the layout.
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;
更新
下面是一个不需要暴露私有类领域更加面向未来的解决方案。
Update
Here is a more future proof solution that doesn't require exposing private class fields.
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;
本例忽略任何自动换行或字符微调。
This example omits any word wrapping or character trimming.
这篇关于如何调整按钮大小以适合在Delphi FireMonkey文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!