在Java中像素字符串长度 [英] String length in pixels in Java

查看:683
本文介绍了在Java中像素字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来计算像素的字符串的长度,给予一定 java.awt.Font中的对象,即不使用任何GUI组件?


解决方案

  

这是不使用任何GUI组件?


这取决于你的意思是在这里。我假设你的意思是你想这样做没有收到一个 HeadlessException的

最好的办法是用的BufferedImage 。据我所知,这不会抛出 HeadlessException的

 字体的字体= ...;
IMG的BufferedImage =新的BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
。FontMetrics对象FM = img.getGraphics()getFontMetrics(字体);
INT宽度= fm.stringWidth(你的字符串);

除了使用这样的事情,我不认为你可以。你需要一个图形上下文,以创建一个的FontMetrics ,并给你的字体大小的信息。

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?

解决方案

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.

这篇关于在Java中像素字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆