Is it possible to obtain the width of text?

(Mike McRoberts) #1

Is there any way of obtaining the width of a string of text, in pixels, prior to printing it so that it can be placed dead centre in the middle of the screen no matter what length it is?

(Scott) #2

If it’s a standard null terminated character array or a quoted string like “my string” and you know the width of a character, including inter-character spacing:

#define CHAR_WIDTH 6 // character width in pixels including inter-character spacing

widthInPixels = strlen("my string") * CHAR_WIDTH; // string length in pixels

(Mike McRoberts) #3

OK but how would I know the widths of the characters?

(Scott) #4

If you’re using the text functions in the Arduboy or Arduboy2 libraries, at size 1 a charater is 5 pixels wide. 1 pixel is added at the end of each character to space them apart, so 6 pixels total width.

Technically, the total width of a string would be 1 pixel less if you don’t want to include the space pixel at the end of the last character, so possibly you would use:

widthInPixels = strlen("my string") * 6 - 1;

(Mike McRoberts) #5

OK thanks i’ll give that a try.