用户登录
用户注册

分享至

字符串(包含中英文、数字、符号)的对齐

  • 作者: 我假装不懂的样子
  • 来源: 51数据库
  • 2021-07-28

我们知道,当字符串中包含中英文、数字、符号时,两行文本即使个数相同,也未必能对齐。UI 看着很不舒服。
写了个对齐函数,让字符串都定长,就对齐了。

{ 获取字符串宽度;包含中英文、数字等 }
function GetStringWidth(const strValue: string; const font: TFont): Integer;
var
  DC      : HDC;
  hSavFont: HFont;
  Size    : TSize;
begin
  DC       := GetDC(0);
  hSavFont := SelectObject(DC, font.Handle);
  GetTextExtentPoint32(DC, PChar(strValue), length(strValue), Size);
  SelectObject(DC, hSavFont);
  ReleaseDC(0, DC);
  Result := Size.cx;
end;

{ 对齐字符串;即固定长度 }
function AlignStringWidth(const strValue: string; const font: TFont; const intMaxLen: Integer = 200): String;
var
  intLen: Integer;
begin
  intLen := GetStringWidth(strValue, font);
  if intLen >= intMaxLen then
    Result := strValue
  else
  begin
    Result := strValue;
    while true do
    begin
      Result := Result + ' ';
      if GetStringWidth(Result, font) >= intMaxLen then
        Break;
    end;
  end;
end;


记录一下。
?

?
软件
前端设计
程序设计
Java相关