我正在尝试在字符串的末尾绘制一个插入符,但我不知道如何检索我使用graphics2d.drawString绘制的给定字符串的尺寸。或者如果有一个“形状”实际上是一个带尺寸的字符串,那将有所帮助,谢谢..
答案 0 :(得分: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;
答案 1 :(得分:1)
您可以尝试这样的事情
Graphics2D g2d = ...
Font font = ...
Rectangle2D r = font.getStringBounds("Your_String!", g2d.getFontRenderContext());
System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");
答案 2 :(得分:0)
您可以使用TextLayout
作为字符串绘图。这与形状非常相似,并且比普通字符串绘图有很多选项。
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);