K
K
krka922019-04-04 16:25:49
Delphi
krka92, 2019-04-04 16:25:49

How to correctly calculate the width of the text?

How can I correctly calculate the width of the text using the Windows API?
The font is NOT monospaced. Arial.
For example: I have some string, let it be "Some string". I'm calculating the width using the GetTextExtentPoint32 function - correct. I calculate the width for the string "11111" - the result is greater than the actual width.
The cant reproduced only for Arial, but the option "Do not use Arial" is not suitable.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
krka92, 2019-04-09
@krka92

Used the DrawText function with the DT_CALCRECT flag

K
Konstantin Tsvetkov, 2019-04-04
@tsklab

function TCustomCanvas.TextWidth(const Text: string): Integer;
begin
  Result := TextExtent(Text).cX;
end;
function TCanvas.TextExtent(const Text: string): TSize;
begin
  RequiredState([csHandleValid, csFontValid]);
  Result.cX := 0;
  Result.cY := 0;
  Winapi.Windows.GetTextExtentPoint32(FHandle, Text, Length(Text), Result);
end;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question