benfry / processing4

Processing 4.x releases for Java 17
https://processing.org
Other
1.35k stars 237 forks source link

Centering text vertically does not work correctly #739

Closed ThexXTURBOXx closed 1 year ago

ThexXTURBOXx commented 1 year ago

Description

textAlign(CENTER, CENTER) does not center text vertically correctly

Expected Behavior

After textAlign(CENTER, CENTER), text should be aligned in the center.

Current Behavior

The text is not centered vertically:

grafik

Steps to Reproduce

  1. Run the following sketch:

    void setup() {
      size(100,100);
    }
    
    void draw() {
      background(0);
      textAlign(CENTER,CENTER);
      textSize(100);
      text("Ap", width/2, height/2);
    }

Your Environment

Possible Causes / Solutions

The issue lies most likely somewhere within these lines: https://github.com/processing/processing4/blob/main/core/src/processing/core/PGraphics.java#L4920-L4926 But I am not sure

SableRaf commented 1 year ago

Hi @ThexXTURBOXx,

Thanks for raising this issue. You're correct that Processing's vertical alignment may not center text perfectly due to the way it handles characters that extend above or below the baseline.

A potential workaround involves calculating the full height of the text, including both ascent and descent, and adjusting the y-position accordingly. However, this method is not ideal as the ascent and descent are based on the tallest and deepest characters (d and p), which may not represent the actual height of your specific string.

A more accurate workaround to get the exact string height involves generating a vector representation for each character, identifying the vertices with the highest and lowest Y positions.

I would recommend taking a look at this excellent StackOverflow post by @micycle. It provides a detailed explanation on this matter and presents potential solutions.