我如何计算像素的字符串的宽度? [英] How do I calculate the width of a string in pixels?

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

问题描述

如何在Java中以像素为单位计算 String 的宽度?例如,我有一个字符串说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 上下文安装的默认字体,如果您需要...


How to calculate width of a String in pixels in Java? For e.g., I have a string say "Hello World!". What is its length in pixels, also considering its font family and size?

解决方案

There are a number of ways to achieve what you want, based on what it is you want to achieve, for example...

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();

But this only has relevence for the BufferedImage and it's Graphics context, it will not translate back to say, something like a screen or printer.

However, so long as you have a Graphics context, you can achieve the same result.

This example, obviously, uses the default font installed for the Graphics context, which you can change if you need to...

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

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