0

我正在尝试在字符串末尾绘制一个插入符号,但我不知道如何检索我正在使用 graphics2d.drawString 绘制的给定字符串的尺寸。或者,如果有一个“形状”实际上是一个带有尺寸的字符串,那会有所帮助,谢谢..

4

3 回答 3

1

像这样的东西:

    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();
    GlyphVector gv = g2d.getFont().createGlyphVector(frc, "YOUR_STRING");
    Rectangle rect = gv.getPixelBounds(null, INITIAL_X, INITIAL_Y);

    int width = rect.width;
    int height = rect.height;
于 2013-08-21T07:22:07.740 回答
1

你可以试试这样的

Graphics2D g2d = ...
Font font = ...
Rectangle2D r = font.getStringBounds("Your_String!", g2d.getFontRenderContext());
System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");
于 2013-08-21T07:26:23.650 回答
0

您可以使用TextLayoutString 绘图。这与形状非常相似,并且比普通的字符串绘图有很多选择。

Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
TextLayout tl = new TextLayout("My String", f, gd2.getFontRenderContext());

// bounds of the TextLayout
Rectangle2D bounds = tl.getBounds();

// draw the text
tl.draw(g2d, x, y)

// position at end
double xEnd = bounds.getWidth() + x;
double yEnd = bounds.getHeight() + y;
Point2D end = new Point2D.Double(bounds.getWidth() + x, bounds.getHeight() + y);
于 2013-08-21T07:33:17.213 回答