2

This is often done in javascript to calculate the width of an item, but for various reasons, I need to give this width to the javascript. The module that I'm using is in C++ (compiled via emscripten), and I was wondering if there are any C++ (or C) libraries that are able to calculate the width of text based on a string of text, font-size, and font-family. For example:

int get_pixel_width(char * str, float font_size, char * font_family);

I know there is something to do this in .net but haven't been able to locate anything in C/C++

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • 3
    This is operating system/GUI toolkit specific, there is no general C or C++ solution. – Gary Sep 17 '19 at 04:53
  • 1
    C and C++ are both platform-agnostic. The language itself doesn't know or care if there's a graphical display, much less it's resolution. You'll need to find a platform-specific library to do this. – paulsm4 Sep 17 '19 at 04:53
  • So you are asking about the width in pixel of a text. I assume that refers to a text representation in a non-fixed-width font. Usually determining this width is part of whatever software creates that representation. Please provide more background information. Whatever porvides the "create text" should also provide something of a width API. – Yunnosch Sep 17 '19 at 04:53
  • Did you look at [this workaround](https://stackoverflow.com/a/118251/3405291)? It requires accessing HTML `div` element properties from within C++ with Emscripten. Not sure if it is possible. – Megidd Sep 17 '19 at 05:11

1 Answers1

1

It is possible to do this in a platform agnostic way. For example, Harfbuzz (in conjunction with a font engine such as FreeType) can take a text string, and compute the size and location of each glyph in the string, taking into account not only kerning and leading, but also things like glyphs in some scripts have different shapes and locations, depending on whether they're at the beginning, middle, or end of a word.

That said, Harfbuzz is still a fairly low-level library that's intended primarily for use by higher level rendering libraries and such. In most cases, whatever you use for rendering will probably provide a higher-level routine that may well be simpler to use than what Harfbuzz has.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111