Archive

Archive for July 20, 2014

Calculating text-metrics with Smart Mobile Studio

July 20, 2014 2 comments

When creating your own custom controls, be they composite controls (built using other components) or purely graphical controls, calculating the width and height of text is important.

Here is a small class I wrote to deal with that topic. Its doesn’t calculate accent and decent, but that could be extracted by comparing to an empty SPAN or DIV. You may also want to reset padding and margin, depending on your stylesheet (so your style doesnt override the default values of the calculated data). Tested in Chrome (webkit).


type

  TQTXTextMetric  = Record
    tmWidth:  Integer;
    tmHeight: Integer;
    function  toString:String;
  End;

  TQTXControlTools = Class
  public
    class function calcTextMetrics(const aText:String;
          const aFontName:String;const aFontSize:Integer):TQTXTextMetric;

    class function calcTextAverage(const aFontName:String;
          const aFontSize:Integer):TQTXTextMetric;
  end;


function TQTXTextMetric.toString:String;
Begin
  result:=Format('width=%d px, height=%d px',[tmWidth,tmHeight]);
end;

class function TQTXControlTools.calcTextAverage(const aFontName:String;
      const aFontSize:Integer):TQTXTextMetric;
Begin
  result:=calcTextMetrics('gWÅzj§',afontName,aFontSize);
end;

class function TQTXControlTools.calcTextMetrics(const aText:String;
  const aFontName:String;const aFontSize:Integer):TQTXTextMetric;
var
  mHandle:  THandle;
Begin
  asm
    @mHandle = document.createElement("span");
  end;

  mHandle.style['display']:='inline-block';
  mHandle.style['visibility']:='hidden';
  mHandle.style['font-family']:=aFontName;
  mHandle.style['font-size']:=TInteger.ToPxStr(aFontSize);

  mhandle.textContent := aText;

  asm
    document.body.appendChild(@mHandle);
  end;

  result.tmHeight := mHandle.offsetHeight;
  result.tmWidth  := mHandle.offsetWidth;

  asm
    document.body.removeChild(@mHandle);
  end;
end;