Announcement

Collapse
No announcement yet.

Centering characters

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • SkiFreak
    replied
    That is perfect Juniel.
    Thanks heaps. 😊

    Leave a comment:


  • Juniel Cruz
    replied
    Good day!

    When using the default fonts, which are monospaced, you can get the width and height of character using the functions Display.charheight and Display.charwidth. From here you can calculate the string width and therefore the string's top-left position that you need. Your code will be something like this:

    Code:
    void putstrCentred(char * str, int x, int y) {
        int len = strlen(str);
        int chrW = Display.charwidth(' ');
        int chrH = Display.charheight(' ');
        int strW = chrW * len;
        int leftPos = x - (strW / 2);
        int topPos = y - (chrH / 2);
        Display.gfx_MoveTo(leftPos, topPos);
        Display.putstr(str);
    }
    When using non-monospaced fonts, you can still use the same method except, the character width will vary. In this case, you can do something like this.


    Code:
    void putstrCentred(char * str, int x, int y) {
        int len = strlen(str);
        int strW = 0;
        for (int i = 0; i < len; i++) {
            strW += Display.charwidth(str[i]);
        }
        int chrH = Display.charheight(' ');
        int leftPos = x - (strW / 2);
        int topPos = y - (chrH / 2);
        Display.gfx_MoveTo(leftPos, topPos);
        Display.putstr(str);
    }
    I hope this helps.

    Best Regards,

    Leave a comment:


  • SkiFreak
    started a topic Centering characters

    Centering characters

    I have looked through the serial command reference but could not find anything that showed a method for centering characters (char value or an int value). Basically centering some text or a number on the screen.
    What I want to do is go to a precise location on the screen (that's easy with Display.gfx_MoveTo), then centre justify some characters at that point. The the vertical positioning is not important (Y axis).
    If this is possible, some sample code would be greatly appreciated.
Working...
X