1

我正在使用 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);

这可以很好地绘制形状和文本,但文本只是一条长线。我希望它整齐地融入多边形。

4

2 回答 2

0

您必须缩放字体大小或/和中断文本。要测量文本宽度,您可以使用:

// get metrics from the graphics
FontMetrics m= g.getFontMetrics(font);
int strWidth = metrics.stringWidth("MyTexxt");
于 2013-09-15T16:38:43.170 回答
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;
    }
}
于 2013-09-16T19:18:13.500 回答