开发者

how to retrieve exact text width for RenderText in Graphics32

开发者 https://www.devze.com 2023-01-31 17:35 出处:网络
I think my question is clear enough, but I explain more. Simply, when we are using AntiAlias on RenderText procedure, the value gotten within TextWidth function is not correct. 开发者_StackOverflow中文

I think my question is clear enough, but I explain more. Simply, when we are using AntiAlias on RenderText procedure, the value gotten within TextWidth function is not correct. 开发者_StackOverflow中文版What can I do to get the right text width?


You can look for the algorithm in their own code. They must also calculate it. Anyway this is how I do it.

function TGR32Canvas.TextWidth(const Text: string): Integer;
var
  TempFont: TFont;
  TempWidth: Integer;
begin
  if Text <> '' then
  begin
    TempFont := TFont.Create;
    try
      TempFont.Assign(Font);
      TempFont.Size := Font.Size shl AA_MODE;
      TempWidth := GetTextWidth(Text, TempFont);
    finally
      TempFont.Free;
    end;
  end
  else
    TempWidth := 0;

  TempWidth := (TempWidth shr AA_MODE + 1) shl AA_MODE;
  Result := TempWidth shr AA_MODE;
end;

The GetTextWidth function is simple. You can do it differently.

function GetTextWidth(const Text: string; const Font: TFont): Integer;
var
  Canvas: TCanvas;
begin
  Canvas := TCanvas.Create;
  try
    Canvas.Handle := GetDC(0);
    try
      Canvas.Font.Assign(Font);
      Result := Canvas.TextWidth(Text);
    finally
      ReleaseDC(0, Canvas.Handle);
    end;
  finally
    Canvas.Free;
  end;
end;


You can also use the Windows API function GetTextExtentPoint32 Do some google to find example on Delphi

0

精彩评论

暂无评论...
验证码 换一张
取 消