Delphi:获取控件⽂本宽度(像素)为适应多语⾔,需要对界⾯控件⼤⼩、位置多动态改变,因此需要根据其Caption计算实际像素⼤⼩。
资料未有易⽤现成的,遂参数其它⽅法,写以函数处之,代码如下:
uses
TypInfo;
function GetTextWidth(AControl: TControl): Integer;
function GetControlFont: TFont;
var
PropInfo: PPropInfo;
begin
Result := nil;
PropInfo := GetPropInfo(AControl.ClassInfo, 'Font');
if Assigned(PropInfo) then
Result := GetObjectProp(AControl, PropInfo) as TFont;
end;
var
sCaption: string;
fnt: TFont;
cvs: TCanvas;
begin
Result := 0;
if not IsPublishedProp(AControl, 'Caption') then Exit;
sCaption := Trim(GetPropValue(AControl, 'Caption', True));
if sCaption = ''then Exit;
fnt := GetControlFont;
if not Assigned(fnt) then Exit;
cvs := TCanvas.Create;
try
cvs.Handle := GetDC(0);
cvs.Font.Assign(fnt);
Result := cvs.TextWidth(sCaption);
finally
cvs.Free;
end;
end;
界⾯可根据控件⽂本长度动态做修正了。⽐如:
btnConvert.Width := GetTextWidth(btnConvert) + 12;
根据上⾯结论,可封装动态修改控件宽度及位置代码,函数如下:
procedure AdjustPostitionAndWidth(ACtrl: TControl; const AAlignment: TAlignment;
AOffSet: Integer);
function Scale(const v: Integer): Integer;
begin
Result := Trunc(v * Screen.PixelsPerInch / 96);
end;
function GetTextWidth: Integer;
function GetControlFont: TFont;
var
PropInfo: PPropInfo;
begin
Result := nil;
PropInfo := GetPropInfo(ACtrl.ClassInfo, 'Font');
if Assigned(PropInfo) then
Result := GetObjectProp(ACtrl, PropInfo) as TFont;
end;
var
sCaption: string;
fnt: TFont;
cvs: TCanvas;
begin
Result := 0;
if not IsPublishedProp(ACtrl, 'Caption') then Exit;
sCaption := Trim(GetPropValue(ACtrl, 'Caption', True));
if sCaption = ''then Exit;
fnt := GetControlFont;
if not Assigned(fnt) then Exit;
cvs := TCanvas.Create;
try
cvs.Handle := GetDC(0);
cvs.Font.Assign(fnt);
Result := cvs.TextWidth(sCaption); finally
cvs.Free;
end;
end;
var
os, tw: Integer;
begin
AOffSet := Scale(AOffSet);
tw := GetTextWidth();
if tw + AOffSet < ACtrl.Width then Exit; os := tw + AOffSet - ACtrl.Width;
ACtrl.Width := tw + AOffSet;
case AAlignment of
taCenter:
delphi trunc函数ACtrl.Left := ACtrl.Left - os div2;
taRightJustify:
ACtrl.Left := ACtrl.Left - os;
end;
end;
如此,多语⾔显未可⽆忧矣!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论