efl*_*les 79 java string-length
如何计算Java中字符串的长度(以像素为单位)?
优选不使用Swing.
编辑:我想使用Java2D中的drawString()绘制字符串,并使用自动换行的长度.
Jon*_*eet 122
如果您只想使用AWT,则使用Graphics.getFontMetrics(可选地指定字体,对于非默认字体)获取a FontMetrics然后FontMetrics.stringWidth查找指定字符串的宽度.
例如,如果您有一个Graphics名为的变量g,您将使用:
int width = g.getFontMetrics().stringWidth(text);
Run Code Online (Sandbox Code Playgroud)
对于其他工具包,您需要向我们提供更多信息 - 它始终与工具包相关.
Olo*_*ark 52
它并不总是需要依赖于工具包,或者并不总是需要使用FontMetrics方法,因为它需要首先获得在Web容器或无头环境中不存在的图形对象.
我在Web servlet中对此进行了测试,它确实计算了文本宽度.
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
...
String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());
Run Code Online (Sandbox Code Playgroud)
将必要的值添加到这些维度以创建任何所需的边距.
使用以下类中的getWidth方法:
import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
class StringMetrics {
Font font;
FontRenderContext context;
public StringMetrics(Graphics2D g2) {
font = g2.getFont();
context = g2.getFontRenderContext();
}
Rectangle2D getBounds(String message) {
return font.getStringBounds(message, context);
}
double getWidth(String message) {
Rectangle2D bounds = getBounds(message);
return bounds.getWidth();
}
double getHeight(String message) {
Rectangle2D bounds = getBounds(message);
return bounds.getHeight();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们来看看完全不同的东西。以下假设使用 arial 字体,并根据字符与宽度的线性插值进行大胆猜测。
// Returns the size in PICA of the string, given space is 200 and 'W' is 1000.
// see https://p2p.wrox.com/access/32197-calculate-character-widths.html
static int picaSize(String s)
{
// the following characters are sorted by width in Arial font
String lookup = " .:,;'^`!|jl/\\i-()JfIt[]?{}sr*a\"ce_gFzLxkP+0123456789<=>~qvy$SbduEphonTBCXY#VRKZN%GUAHD@OQ&wmMW";
int result = 0;
for (int i = 0; i < s.length(); ++i)
{
int c = lookup.indexOf(s.charAt(i));
result += (c < 0 ? 60 : c) * 7 + 200;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
有趣,但可能不太实用。
| 归档时间: |
|
| 查看次数: |
124224 次 |
| 最近记录: |