[英]How do you find out the height and width of a PFont string in Processing or Java?
如何在 Processing 或 Java 中找出 PFont 字符串的高度和寬度?
當您有這樣的問題時,您可以做的最好的事情是通讀處理參考。
具體來說,您可能正在尋找textWidth()
、 textAscent()
和textDescent()
函數。
size(400, 400);
textSize(36);
String str = "Hello world";
float x = 100;
float y = 100;
float strWidth = textWidth(str);
float strAscent = textAscent();
float strDescent = textDescent();
float strHeight = strAscent + strDescent;
rect(x, y - strAscent, strWidth, strHeight);
fill(0);
text(str, x, y);
使用內置函數textWidth()
、 textAscent()
和textDescent()
是獲得字符串高度和寬度的良好近似結果的簡單方法,但它們並不精確。
為什么?
textAscent()
根據字母 'd'返回行上方的文本高度textDescent()
根據字母 'p'返回行下方的文本高度。textWidth()
包括字形空白(又名填充;理想情況下,我們希望忽略第一個和最后一個字符) textAscent() + textDescent()
因此測量給定字體和字體大小的字符串的最大高度,而不是特定字符串的高度。 換句話說,如果您的文本不包含 'd' 和 'p' 字符,那么使用這些方法來確定文本高度將高估結果(正如我們在 Kevin 的屏幕截圖中看到的那樣)。
我們可以使用這種方法來獲得高度的准確結果:
請注意,您需要為此明確創建一個PFont
。
String string = "Hello world";
PFont font = createFont("Arial", 96, true); // arial, size 96
textFont(font);
float minY = Float.MAX_VALUE;
float maxY = Float.NEGATIVE_INFINITY;
for (Character c : string.toCharArray()) {
PShape character = font.getShape(c); // create character vector
for (int i = 0; i < character.getVertexCount(); i++) {
minY = min(character.getVertex(i).y, minY);
maxY = max(character.getVertex(i).y, maxY);
}
}
final float textHeight = maxY - minY;
結果
(注意我們這里仍然使用textWidth()
作為寬度)
text(string, mouseX, mouseY);
rect(mouseX, mouseY, textWidth("Hello world"), -textHeight);
String string = "Hello world";
PFont font = createFont("Arial", 96, true); // arial, size 96
textFont(font);
float textWidth = textWidth(string); // call Processing method
float whitespace = (font.width(string.charAt(string.length() - 1)) * font.getSize()
- font.getGlyph(string.charAt(string.length() - 1)).width) / 2;
textWidth -= whitespace; // subtract whitespace of last character
whitespace = (font.width(string.charAt(0)) * font.getSize() - font.getGlyph(string.charAt(0)).width) / 2;
textWidth -= whitespace; // subtract whitespace of first character
結果
(把兩個放在一起……)
text(string, mouseX, mouseY);
rect(mouseX + whitespace, mouseY, textWidth, -textHeight);
圍繞"Hello world"
繪制的矩形恰好對齊,因為沒有任何字形低於基線。
對於像@#'pdXW\\
這樣的字符串, @
和p
下降到基線以下,這樣矩形雖然是正確的高度,但與 y 軸上的字符串不對齊,如下所示:
一種確定 y 偏移量的編程方法是找到最低的 Y 坐標(盡管記住處理的 y 軸向下延伸,所以我們實際上是在尋找最高值) vertex 。 幸運的是,這是計算得出准確高度的一部分。
我們可以簡單地使用在那里計算的maxY
值來偏移文本邊界框。
結果
text(string, mouseX, mouseY);
rect(mouseX + whitespace, mouseY + maxY, textWidth, -textHeight);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.