Pergunta

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. What can I do to get the right text width?

Foi útil?

Solução

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;

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top