takkaO / OpenFontRender

TTF font render support library for microcomputer.
Other
105 stars 16 forks source link

Cursor x resting place calculated too far right after cprintf (w/ proposed solution) #20

Open MikeyMoMo opened 1 year ago

MikeyMoMo commented 1 year ago

The solution seems easy. I will give that here, then state the details of the problem. (This came up from the full demo code program I am writing)

When using cprintf, you are adding the entire string length to get the cursor x resting spot. You should only add half of the string length to get to the right end. This has been tested in my code, not by modifying the library. I have not tried this with drawString yet. Not sure if it even applies. But, if so, the same solution is proposed.

Now, the problem as it presents itself...

The first one, using printf, calculates the resting point of the cursor properly. The cursor repositioning then appends the font size where it should be, at the right of the second line ("World").

Cursor starting at 0,0. iota result 34, cursor ending location 192/24.

Helllo World 34

But the second one, using cprintf, calculates a cursor resting spot way too high for the width (x) value. The Y value is correct. I proved Y is correct by overriding the x cursor value with 400. It then appeared on screen.

iota result 34, cursor ending location 636/106. The text string width is 380. By subtracting 1/2 of that, the proper cursor x resting spot is obtained (446).

// Alignment left
  render.setCursor(0, 0);
  render.printf("Hello\nWorld size ");  // Seems to be required...
  // If you want to chain text together, use the cursor position after printer to add on.
  x = render.getCursorX(); y = render.getCursorY();  // returns 192 for x and 24 for y.  The append is perfect.

  itoa (font_size, str_buf, 10);
  Serial.printf("iota result %s, cursor ending location %i/%i\r\n", str_buf, x, y);
  // Append font size
  render.setCursor(x, y); render.printf(str_buf);

  // Alignment Center
  render.setCursor(tft.width() / 2, tft.height() / 3); render.setFontColor(TFT_GREEN);
  render.cprintf("Comic_Sans_Italic size ");
  // If you want to chain text together, use the returned cursor position after cprintf to add on.
  x = render.getCursorX(); y = render.getCursorY();  // Returns 636 for x (way wrong) and 106 for y (right). The append is off screen.
  itoa (font_size, str_buf, 10);
  Serial.printf("iota result %s, cursor ending location %i/%i\r\n", str_buf, x, y);
  // Append font size
  render.setCursor(x, y); render.printf(str_buf);
MikeyMoMo commented 1 year ago

The full demo program is now on Github, here:

https://github.com/MikeyMoMo/OpenFontRender-Demo-program