如何计算字符串的宽度(以像素为单位)?
如何计算Java中像素的宽度(以像素为单位)? 例如,我有一个字符串说“Hello World!”。 它的长度(以像素为单位)是多少,还要考虑它的字体系列和大小?
根据你想要实现的目标,有很多方法可以实现你想要的东西,例如……
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
上下文安装的默认字体,如果需要,可以更改…
简而言之:问题取决于您使用的框架。 例如,如果您使用的是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() + ")");
请参阅此文档 ,可能对您有所帮助。
有几种方法可以做,你可以试试label.getElement().getClientWidth();
如果文本是标签,如果你使用的是AWT,你可以使用Graphics.getFontMetrics
然后使用FontMetrics.stringWidth
您可以使用FontMetrics 。 FontMetrics类定义字体度量对象,该对象封装有关特定字体在特定屏幕上呈现的信息。
你可以做类似下面的事情
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();