M5. Lcd.textWidth does not center text exactly in the middle
-
I want to write a text centered in the middle. the text has a variable size. with M5. Lcd.textWidth, the text is not centered exactly in the middle (deviation about 5px). I doing something wrong? How can I center the text in height?
void loop() {
M5.Lcd.fillScreen(BLACK); //set the default background color
M5.Lcd.fillRoundRect(20, 50, 280, 140, 15, RED);
M5.Lcd.fillRoundRect(30, 60, 260, 120, 15, BLACK);
M5.Lcd.setTextSize(5);
M5.Lcd.setTextColor(RED);
for (int i=-1500; i <= 2255; i++){
String text = String(i);
M5.Lcd.fillRoundRect(30, 60, 260, 120, 15, BLACK);
M5.Lcd.drawString(text, (int)((M5.Lcd.width()/2)-(M5.Lcd.textWidth(text)/2)), (int)(M5.Lcd.height()/2), 2);
delay(20);
}
} -
Hello@Stoni99
- Use the setTextDatum and drawString instructions.
M5.Lcd.setTextDatum(3);
M5.Lcd.drawString(text, (int)((M5.Lcd.width()/2)-(M5.Lcd.textWidth(text)/2)-15),(int)(M5.Lcd.height()/2-0), 2);
:
2. Use the drawCentreString instruction.
// M5.Lcd.setTextSize(5);
// M5.Lcd.drawString(text, (int)((M5.Lcd.width()/2)-(M5.Lcd.textWidth(text)/2)), (int)(M5.Lcd.height()/2), 2);M5.Lcd.drawCentreString(text, M5.Lcd.width()/2, M5.Lcd.height()/2-40 , 8);
- Use the setTextDatum and drawString instructions.
-
OK - thank you!
The height is therefore adjusted by hand.Other question:
I can't append the "W" to the string. It is not displayed. Is there another possibility?for (int i=-1500; i <= 2255; i++){
String text = String(i)+"W";
M5.Lcd.fillRoundRect(30, 60, 260, 120, 15, BLACK);
M5.Lcd.drawCentreString(text, M5.Lcd.width()/2, M5.Lcd.height()/2-30 , 7); //Text auf x zentrieren (x,y,Schriftgrösse)
//M5.Lcd.drawString(text, (int)((M5.Lcd.width()/2)-(M5.Lcd.textWidth(text)/2)-15), (int)((M5.Lcd.height()/2)-40), 2);
delay(1000);
} -
Hello@Stoni99
m5-docs:LCD
setTextDatum(), drawString(), drawCentreString()
https://github.com/m5stack/m5-docs/blob/master/docs/en/api/lcd.md:
A. Use the drawCentreString instruction.
The height is therefore adjusted by hand.
drawCentreString : fontname=2M5.Lcd.setTextSize(5);
M5.Lcd.drawCentreString(text, M5.Lcd.width()/2, M5.Lcd.height()/2 -42 , 2);
or
M5.Lcd.setTextSize(4);
M5.Lcd.drawCentreString(text, M5.Lcd.width()/2, M5.Lcd.height()/2 -34 , 2);:
B. setTextDatum + drawString + Free_Fonts
Free_Fonts.h : Beautiful font.
https://github.com/m5stack/M5Stack/blob/master/examples/Advanced/Display/Free_Font_Demo/Free_Fonts.h#include <Free_Fonts.h>
void setup(){
M5.Lcd.setFreeFont(FMB24); // or FM24void loop(){
M5.Lcd.setTextSize(1);
M5.Lcd.setTextDatum(3);
M5.Lcd.drawString(text, M5.Lcd.width()/2-M5.Lcd.textWidth(text)/2, M5.Lcd.height()/2 -3,1); -
👍Thank you!