String length in pixels in Java

巧了我就是萌 提交于 2019-12-19 05:17:06

问题


Is there a way to calculate the length of a string in pixels, given a certain java.awt.Font object, that does not use any GUI components?


回答1:


that does not use any GUI components?

It depends on what you mean here. I'm assuming you mean you want to do it without receiving a HeadlessException.

The best way is with a BufferedImage. AFAIK, this won't throw a HeadlessException:

Font font = ... ;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
FontMetrics fm = img.getGraphics().getFontMetrics(font);
int width = fm.stringWidth("Your string");

Other than using something like this, I don't think you can. You need a graphics context in order to create a FontMetrics and give you font size information.




回答2:


You can use the Graphics2D object to get the font bounds (including the width):

Graphics2D g2d = ...
Font font = ...
Rectangle2D f = font.getStringBounds("hello world!", g2d.getFontRenderContext());

But that depends on how you will get the Graphics2D object (for example from an Image).




回答3:


This gives the output of (137.0, 15.09375) for me. I have no idea what the units are, but it certainly looks proportionally correct and doesn't use Graphics2D directly.

    Font f = new Font("Ariel", Font.PLAIN, 12);
    Rectangle2D r = f.getStringBounds("Hello World! Hello World!", new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT));
    System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")"); 


来源:https://stackoverflow.com/questions/13345712/string-length-in-pixels-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!