Home > OP4JS > Calculating text-metrics with Smart Mobile Studio

Calculating text-metrics with Smart Mobile Studio

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;

Advertisements
  1. abouchez
    August 22, 2014 at 4:22 pm

    Why not just use HTML canvas measureText() Method?

    • Jon Lennart Aasenden
      August 22, 2014 at 5:12 pm

      A bit expensive if you want to size a DIV. Faster to create a PRE element and read the scrollsize

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: