使用 Delphi 计算文本宽度,包括 space / 字符之间的字距调整

Calculating text width including space / kerning between characters using Delphi

我很难找到任何资源来解释如何计算具有不同 kearning / space-字符之间的字符串的文本宽度。

Textwidth 可以使用字体大小、字体样式等,但不能 space 字符之间? (或者我认为字距调整 非常 字体特定,即根据字体给出不同的像素值,因为字符可以 "overlap" 或多或少取决于 kerning/spacing 值)

编辑:推荐阅读:Feng Yuan "Windows Graphics Programming"

TextWidth (GetTextExtentPoint32) 示例和更复杂的方法:

var
  Len, w: Integer;
  s: string;
  GR: TGCPResults;
begin
  Canvas.Font.Size := 14;
  s := 'A simple test string';
  Canvas.TextOut(0, 0, s);
  w := Canvas.TextWidth(s);
  Canvas.MoveTo(w, 0);
  Canvas.LineTo(w, 30);

  SetTextCharacterExtra(Canvas.Handle, 5);
  Canvas.TextOut(0, 30, s);
  w := Canvas.TextWidth(s);
  Canvas.MoveTo(w, 30);
  Canvas.LineTo(w, 60);

  SetTextCharacterExtra(Canvas.Handle, 0);
  Len := Length(s);
  GR.lStructSize := sizeOf(GR);
  GetMem(GR.lpOutString, (Len + 1) * sizeOf(Char));
  GR.lpOrder := Nil;
  GetMem(GR.lpDx, (Len + 1) * sizeOf(Integer));
  GetMem(GR.lpCaretPos, (Len + 1) * sizeOf(Integer));
  GR.lpClass := Nil;
  GetMem(GR.lpGlyphs, (Len + 1) * sizeOf(UINT));
  GR.nGlyphs := Len;
  GR.nMaxFit := 0;

  w := GetCharacterPlacement(Canvas.Handle, PwideChar(s), Len, 0, GR,
    GCP_USEKERNING) and $FFFF;
  ExtTextOut(Canvas.Handle, 0, 60, ETO_GLYPH_INDEX, nil, PChar(GR.lpGlyphs),
    GR.nGlyphs, PINteger(GR.lpDx));
  Canvas.MoveTo(w, 60);
  Canvas.LineTo(w, 90);
  // free memory for GR members