0

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

Textwidth 可以使用字体大小、字体样式等,但不能使用字符之间的空格?(或者我认为非常特定于字体的字距调整,即根据字体给出不同的像素值,因为字符可以根据字距调整/间距值或多或少地“重叠”)

4

1 回答 1

2

编辑:推荐阅读:冯远《Windows图形编程》

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
于 2015-05-23T15:17:07.347 回答