[英]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.