Shraddha K
Shraddha K

Reputation: 97

Width of string in Pixels

Can anyone tell how can I calculate width of a string in pixels,provided font size in pixels? I have to do it in C under linux?

Upvotes: 1

Views: 2542

Answers (3)

LSerni
LSerni

Reputation: 57388

You can't do that by yourself, unless you have a fixed point font (where every character is always X pixels wide). In that case, of course total width = PixelPerChar * strlen(String).

In the general case of proportional fonts, and if characters may be "pushed close" to one another, for example A and V (an operation called "kerning"), you need to ask to the font rendering library, e.g. libGD2. Such libraries usually supply the bounding box of a string, given the font file, size, orientation and other parameters.

Example for GD2 using gdImageStringFT:

int bbox[8]; // x,y of the rectangle bounding the text:
// see manual

gdImageStringFT(NULL,  // "Tell me only"
      bbox,0,
      "/home/lserni/fonts/Verdana.ttf",18,
      0.0,0,0,"Hello world"); 

if (checks on bbox OK)
{
   gdImageStringFT(gdHandle, bbox, 0, ...);
}

Upvotes: 4

Otto Allmendinger
Otto Allmendinger

Reputation: 28268

You probably need something like the FreeType library

Upvotes: 0

Alex
Alex

Reputation: 1684

In the most basic scenario, assuming it is a fixed length font:

int string_width = strlen(str) * CHAR_WIDTH_PX;

Where str is the C string and CHAR_WIDTH_PX is the character width of the font.

But of course in different frameworks and systems things are done in different ways. To help you with that, we need more information about your environment.

Upvotes: 1

Related Questions