U8g2: Alignment for text

Created on 2 Sep 2019  路  7Comments  路  Source: olikraus/u8g2

Hi 馃槉
I need to align words with a function (for example: center align, left align and etc), but I didn't find any specific function for this. I tested many ways to align words (Especially UTF-8 words). The main problem is how to find the width of a word for example in font size 16 or etc. [As we know, changing the font changes the number of pixels used.]
Is there a way to auto alignment words?

Thanks for this great library.

Most helpful comment

Problem solved with some changes.
Thank you for your attention. The following code can be used to alignment the UTF-8 letters (especially right-to-left languages like Arabic and Persian).

#define LCDWidth                        u8g2.getDisplayWidth()
#define ALIGN_CENTER(t)                 ((LCDWidth - (u8g2.getUTF8Width(t))) / 2)
#define ALIGN_RIGHT(t)                  (LCDWidth -  u8g2.getUTF8Width(t))
#define ALIGN_LEFT                      0

All 7 comments

There is getUTF8Width() function here: https://github.com/olikraus/u8g2/wiki/u8g2reference#getutf8width
It calculates the width of the provided string. If you pass the word itself, it will return the pixel width. Of course you need to set the font before calling this function.

Note: getUTF8Width() is not 100% correct, it might be wrong by 1 or 2 pixel.

Thanks.
I had seen this function on the wiki and I did a lot of testing but getUTF8Width() does not work right. but I'll test again and say the result.

Problem solved with some changes.
Thank you for your attention. The following code can be used to alignment the UTF-8 letters (especially right-to-left languages like Arabic and Persian).

#define LCDWidth                        u8g2.getDisplayWidth()
#define ALIGN_CENTER(t)                 ((LCDWidth - (u8g2.getUTF8Width(t))) / 2)
#define ALIGN_RIGHT(t)                  (LCDWidth -  u8g2.getUTF8Width(t))
#define ALIGN_LEFT                      0

:)

Petition to add this functionality directly to the library

It should not take much effort to implement this by yourself.

sure - I can make a PR for it

Was this page helpful?
0 / 5 - 0 ratings

Related issues

morosanl picture morosanl  路  3Comments

margce picture margce  路  7Comments

Audio-Rochey picture Audio-Rochey  路  4Comments

hauwarea picture hauwarea  路  5Comments

hilsonp picture hilsonp  路  3Comments