仅在顶部和左侧使用锚点。然后在WMExitSizeMove消息过程中使用以下代码:
Label1.Height := (Label1.Height * Height) div OldHeight;
,并将
Width
用作缩放系统。然后使用David的答案来使用缩放更新字体(使用OPs评论中的pasteBin函数)。这对于简单的缩放系统非常有效。如果只更改宽度或高度时字体不进行缩放会影响您,则可以在该情况下停止标签的缩放。
以下代码翻译成我所说的话。
unit Unit12;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, system.Math;
type
TForm12 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
procedure WMExitSizeMove(var aMessage: TMessage); message WM_ExitSizeMove;
public
end;
var
Form12: TForm12;
OldWidth, OldHeight: Integer;
implementation
{$R *.dfm}
function CalculateMazSize(aCanvas: TCanvas; aText: string; aWidth, aHeight: Integer): Integer;
function LargestFontSizeToFitWidth(aCanvas: TCanvas; aText: string; aWidth: Integer): Integer;
var
Font: TFont;
FontRecall: TFontRecall;
InitialTextWidth: Integer;
begin
Font := aCanvas.Font;
Result := Font.Size;
FontRecall := TFontRecall.Create(Font);
try
InitialTextWidth := aCanvas.TextWidth(aText);
Font.Size := MulDiv(Font.Size, aWidth, InitialTextWidth);
if InitialTextWidth < aWidth then
while True do
begin
Font.Size := Font.Size + 1;
if aCanvas.TextWidth(aText) > aWidth then
exit(Font.Size - 1);
end;
if InitialTextWidth > aWidth then
begin
while True do
begin
Font.Size := Font.Size - 1;
if aCanvas.TextWidth(aText) <= aWidth then
exit(Font.Size);
end;
end;
finally
FontRecall.Free;
end;
end;
function LargestFontSizeToFitHeight(aCanvas: TCanvas; aText: string; aHeight: Integer): Integer;
var
Font: TFont;
FontRecall: TFontRecall;
InitialTextHeight: Integer;
begin
Font := aCanvas.Font;
Result := Font.Size;
FontRecall := TFontRecall.Create(Font);
try
InitialTextHeight := aCanvas.TextHeight(aText);
Font.Size := MulDiv(Font.Size, aHeight, InitialTextHeight);
if InitialTextHeight < aHeight then
while True do
begin
Font.Size := Font.Size + 1;
if aCanvas.TextHeight(aText) > aHeight then
exit(Font.Size - 1);
end;
if InitialTextHeight > aHeight then
while True do
begin
Font.Size := Font.Size - 1;
if aCanvas.TextHeight(aText) <= aHeight then
exit(Font.Size);
end;
finally
FontRecall.Free;
end;
end;
begin
if aText <> '' then
Result := Min(LargestFontSizeToFitWidth(aCanvas, aText, aWidth),
LargestFontSizeToFitHeight(aCanvas, aText, aHeight))
else
Result := aCanvas.Font.Size;
end;
procedure TForm12.FormCreate(Sender: TObject);
begin
OldWidth := Width;
OldHeight := Height;
end;
procedure TForm12.WMExitSizeMove(var aMessage: TMessage);
begin
Label1.Height := (Label1.Height * Height) div OldHeight;
Label1.Width := (Label1.Width * Width) div OldWidth;
Label1.Font.Size := CalculateMazSize(Label1.Canvas, Label1.Caption, Label1.Width, Label1.Height);
OldWidth := Width;
OldHeight := Height;
end;
end.
这个问题的一个问题是,如果用户最大化表单,则无法工作,因为根据文档,只有在用户调整大小或移动表单时才会发送此消息。
在窗口退出移动或调整大小模态循环后,向窗口发送一次。当用户单击窗口的标题栏或调整大小边框,或者窗口将WM_SYSCOMMAND消息传递给DefWindowProc函数并且消息的wParam参数指定SC_MOVE或SC_SIZE值时,窗口进入移动或调整大小模态循环。当DefWindowProc返回时,操作完成。