Accurately calculate text width in metric units

I want to calculate the exact width of the text in metric units of a given string. My pseudo code is as follows:

Bitmap.Canvas.Assign(Font);
PixelWidth := Bitmap.Canvas.TextWidth(Font)
MetricWidth := PtToMM * (PixelWidth * 72.0 / GetScreenDPI);

PtToMMis a constant that is defined as 0.352777778. This is pretty accurate for some fonts and font sizes, but for others it is too small or too large. I experimented a lot with other features, such as GetCharWidth32and GetCharABCWidthsalso with the display mode MM_LOMETRIC, but I just can't get it to work. This problem haunts me, so please someone can help and show me where I am wrong. Thank you very much!

EDIT I checked one line: the width of the metric is calculated as 4.17 cm, the width of the actual printout (measured on paper) is 4.4 cm (font Times New Roman, size 12).

+5
source share
1 answer

I did not test it extensively, but it seems that it gave the correct results. The result is the width of the text in a thousandth of a millimeter. This feature does not support word wrap and other special considerations.

Also note that when working with the printer, incorrect print registration can “stretch” the text.

Also note that for a printer, changing, for example, print resolution from 300 ppp to 1200 ppp will also change the result.

uses
  ConvUtils, stdConvs ;

function CalcRequiredTextWidth(aDC : HDC; aFont : TFont; const asText: string): Double;
var vCanvas : TCanvas;
    iPixelsWidth : Integer;
    dInchWidth : Double;
    iFontSize : Integer;
begin
  vCanvas := TCanvas.Create;
  try
    vCanvas.Handle := aDC;

    vCanvas.Font.Assign(aFont);
    iFontSize := vCanvas.Font.Size;
    vCanvas.Font.PixelsPerInch := GetDeviceCaps(aDC, LOGPIXELSY);
    vCanvas.Font.Size := iFontSize;

    iPixelsWidth := vCanvas.TextExtent(asText).cx;

    dInchWidth := iPixelsWidth / GetDeviceCaps(vCanvas.Handle, LOGPIXELSX);

    Result := Convert(dInchWidth, duInches, duMicrons);

  finally
    vCanvas.Free;
  end;
end;
0
source

All Articles