如何在Java中计算字符串的像素宽度?例如,我有一个字符串“Hello World!”。考虑其字体和大小,它的像素长度是多少?
简而言之:问题取决于您使用的框架。例如,如果您正在使用AWT,并且拥有一个Graphics
对象graphics
和一个Font
对象font
,则可以执行以下操作:
FontMetrics metrics = graphics.getFontMetrics(font);
int width = metrics.stringWidth("Hello world!");
点击这里了解更多信息。
Graphics2D g2d = ...
Font font = ...
Rectangle2D r = font.getStringBounds("hello world!", g2d.getFontRenderContext());
System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");
Graphics#getFontMetrics
,但我会点赞给你,因为你与众不同 ;) - MadProgrammer根据您想要实现的目标,有多种方法可供选择,例如...
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
FontMetrics fm = g2d.getFontMetrics();
System.out.println(fm.stringWidth("This is a simple test"));
g2d.dispose();
BufferedImage
及其Graphics
上下文有关,它不会转换回屏幕或打印机等其他内容。Graphics
上下文,就可以实现相同的结果。Graphics
上下文安装的默认字体,如果需要,您可以更改它...String
。我知道它的长度、字体和字号。我想要计算它在像素上的大小。 - user2550754Graphics
上下文。虽然你有字体系列、字体大小和文本,但你缺少关键元素。 - MadProgrammer Font font = new Font("Verdana", Font.PLAIN, 10);
FontMetrics metrics = new FontMetrics(font) {
};
Rectangle2D bounds = metrics.getStringBounds("Hello World!", null);
int widthInPixels = (int) bounds.getWidth();
有几种方法可以实现,如果文本在标签中,您可以尝试使用label.getElement().getClientWidth();
。如果您正在使用AWT,则可以使用Graphics.getFontMetrics
然后使用FontMetrics.stringWidth
FontMetrics#stringWidth
。 - MadProgrammer