使用 Java,是否有任何内置的方法来呈现文本以使其仅限于 graphics2D
对象上的矩形?
我知道我可以使用 Graphics2D.drawString
但它只能绘制一行文本。
我也知道我可以用
FontMetrics fm= graphics.getFontMetrics(font);
Rectangle2D rect=fm.getStringBounds("Some Text",graphics);
在某些 Graphics2D 图形
对象上使用某些 Font 字体
呈现时获取有关字符串边界的信息。
所以我可以开始循环,断开我的字符串等等,以强制它适合某个矩形。
但我宁愿不必写那些...
是否有任何现成的函数可以为我执行此操作?
最佳答案
我写了一个可以提供帮助的小函数。 447 是可用宽度,您可以从所需的宽度中获取以在其上呈现文本。
private void drawTextUgly(String text, FontMetrics textMetrics, Graphics2D g2)
{
// Ugly code to wrap text
int lineHeight = textMetrics.getHeight();
String textToDraw = text;
String[] arr = textToDraw.split(" ");
int nIndex = 0;
int startX = 319;
int startY = 113;
while ( nIndex < arr.length )
{
String line = arr[nIndex++];
while ( ( nIndex < arr.length ) && (textMetrics.stringWidth(line + " " + arr[nIndex]) < 447) )
{
line = line + " " + arr[nIndex];
nIndex++;
}
GraphicsUtility.drawString(g2, line, startX, startY);
startY = startY + lineHeight;
}
}
关于java - 我如何在 java 中渲染图像上的包装文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12129633/