我正在使用Java Graphics2D绘制基本和复杂的多边形,其中包含不同长度和字体的文本。我想要实现的是绘制的文本被完美地包裹并剪裁以适合多边形。
到目前为止我的代码是:
int[] xp = { x + width /2, x + width -1, x };
int[] yp = { y, y + height - 1, y + height - 1 };
g.setColor(fill.color1);
g.fillPolygon(xp, yp, xp.length);
g.setColor(border.color);
g.setStroke(new BasicStroke((float) (border.width * zoom), BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
g.drawPolygon(xp, yp, xp.length);
// Later on in the method..
g.drawString(text, textx, texty);
这样可以很好地绘制形状和文本,但文本只是一条长线。我希望它整齐地适合多边形。
答案 0 :(得分:0)
您必须缩放字体大小或/和中断文本。 要测量文本宽度,您可以使用:
// get metrics from the graphics
FontMetrics m= g.getFontMetrics(font);
int strWidth = metrics.stringWidth("MyTexxt");
答案 1 :(得分:0)
这个解决方案对我来说效果很好。我使用了alhugone的建议并决定计算文本应该放在Shape中的哪个位置。这就是我所做的:
public static void wrapTextToPolygon(Graphics2D g, String text, Font font, Color color, java.awt.Shape shape, int x, int y, int border)
{
FontMetrics m = g.getFontMetrics(font);
java.awt.Shape poly = shape;
int num = 0;
String[] words = new String[1];
if(text.contains(" "))
{
words = text.split(" ");
}
else words[0] = text;
int yi = m.getHeight() + border;
num = 0;
while(num != words.length)
{
String word = words[num];
Rectangle rect = new Rectangle((poly.getBounds().width / 2) - (m.stringWidth(word) / 2) + x - border - 1, y + yi, m.stringWidth(word) + (border * 2) + 2, m.getHeight());
while(!poly.contains(rect))
{
yi += m.getHeight();
rect.y = y + yi;
if(yi >= poly.getBounds().height) break;
}
int i = 1;
while(true)
{
if(words.length < num + i + 1)
{
num += i - 1;
break;
}
rect.width += m.stringWidth(words[num + i]) + (border * 2);
rect.x -= m.stringWidth(words[num + i]) / 2 - border;
if(poly.contains(rect))
{
word += " " + words[num + i];
}
else
{
num += i - 1;
break;
}
i = i + 1;
}
if(yi < poly.getBounds().height)
{
g.drawString(word, (poly.getBounds().width / 2) - (m.stringWidth(word) / 2) + x, y + yi);
}
else
{
break;
}
yi += m.getHeight();
num += 1;
}
}