Center Align String

Hello again,

I found nothing related in this forum:

how would I center align a string?

lets say I have 5 words, each one in a box of 25 px, so I can write 5 words on the 128px oled, with a centered fader below.

I have seen WriteStringAligned, but it is so cryptic and does not mention Center.

Has anybody mastered this already?

Thanks!

Here is an example of Chat GPT having a go at it, but chatty likes to over-complicate things and it can´t get over the fact that here is no argument “center” here.

// Define the width of the bounding box and starting position
const int boundingBoxWidth = 25;  // Width of each bounding box
const int boundingBoxHeight = Font_6x8.FontHeight; // Height of bounding box
const int startY = 2;            // y position
const int displayWidth = 128;    // Width of the display

// Define text array and positions
const char* texts[] = {"Size", "Tail", "HP", "LP", "Lvl"};
int numTexts = sizeof(texts) / sizeof(texts[0]);

// Starting position for the first bounding box
int startX = 2;

// Iterate over each text and position
for (int i = 0; i < numTexts; i++) {
    // Calculate the bounding box for the current text
    Rectangle boundingBox(startX, startY, startX + boundingBoxWidth - 1, startY + boundingBoxHeight - 1);
    
    // Align and write the text within the bounding box
    WriteStringAligned(texts[i], Font_6x8, boundingBox, Center, true);

    // Update x position for the next bounding box
    startX += boundingBoxWidth + 1;  // Move to the next position (25 px width + 1 px space)
}

here is a manual solution, without trying to fight WriteStringAligned.

but it´s a lot of code, might it be possible with less?

// Define font and text
const FontDef& font = Font_6x8;  // Replace with your actual font
const int boundingBoxWidth = 25;

// Define text array and starting positions
const char* texts[] = {"Size", "Tail", "HP", "LP", "Lvl"};
int xPositions[] = {2, 27, 52, 77, 102};  // Starting x positions for each text

// Iterate over each text and position
for (int i = 0; i < 5; i++) {
    // Calculate text width
    int textWidth = strlen(texts[i]) * font.FontWidth;

    // Calculate x position to center the text in the bounding box
    int x = xPositions[i] + (boundingBoxWidth - textWidth) / 2;

    // Set the cursor position and write the string
    display.SetCursor(x, 2);
    display.WriteString(texts[i], font, true);
}