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?
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
OK but how would I know the widths of the characters?
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;
OK thanks i’ll give that a try.
How would you actually print the text in the center though?
Â
I read this to find out how to print the text in the center of the screen as I am making the title screen of a game.
A bit like so:
                                              Welcome to blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
Here is a small Hello World example:
Arduboy2 arduboy;
const int CHAR_WIDTH = 6;
const int CHAR_HEIGHT = 8;
String text = "Hello World!";
// Center horizontally
int x = (WIDTH - (text.length()*CHAR_WIDTH - 1))/2;
// Center vertically
int y = (HEIGHT - (CHAR_HEIGHT))/2;
arduboy.setCursor(x, y);
arduboy.print(text);
Thank you! I will try this now
(I turned off notifications)
I wrote a bunch of string-measuring and centre-finding functions for Minesweeper:
(See FontUtils.h
and ScreenUtils.h
.)
So basically you do:
const char someString[] = "Some text";
void function()
{
// All calculated at compile time
constexpr uint8_t stringWidth = StringWidth(someString);
constexpr uint8_t stringHeight = StringHeight(1);
constexpr uint8_t x = CalculateCentreX(stringWidth);
constexpr uint8_t y = CalculateCentreY(stringHeight);
// This will draw the text in the centre of the screen
arduboy.setCursor(x, y);
arduboy.print(AsFlashString(someString));
}
Unfortunately you’d have to grab at least 4-5 files from Minesweeper’s Utils
folder for it to work.
If you can wait a bit I could put together something smaller (i.e. just one or two files).
Avoid using String
, it uses dynamic allocation so it eats more memory than necessary.