从宽度的Java字体大小 [英] Java font size from width
问题描述
Font.PLAIN
,我想要得到最适合我的宽度为100像素的字体大小。 我知道我可以在循环中计算它(类似于 while(font.getSize()< panel.getWidth() code>),但说实话我并不觉得它非常优雅。
使用FontMetrics类的字符串的宽度和高度(确保在Graphics2D实例中启用小数字体度量以避免舍入错误):
Graphics2D g = ...;
g.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
Font font = Font.decode( Times New Roman);
String text =Foo;
Rectangle2D r2d = g.getFontMetrics(font).getStringBounds(text,g);
现在,当您使用字体的宽度为e默认(或者实际上是任何)尺寸,可以缩放字体,以使文本适合指定的宽度。 100px:
font = font.deriveFont((float)(font.getSize2D()* 100 / r2d.getWidth()) );
同样,您可能需要限制字体大小,以免超过可用面板
为了改善渲染文本的外观,您还应该考虑为字体中的文本渲染和/或字距支持启用抗锯齿功能:
g.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
映射< TextAttribute,Object> atts = new HashMap< TextAttribute,Object>();
atts.put(TextAttribute.KERNING,TextAttribute.KERNING_ON);
font = font.deriveFont(atts);
I'm looking for a way to infer a Java AWT Font size from a width. For example, I know I want to write 'hello world' within 100 pixels. I know I'm using the font "Times", in style Font.PLAIN
, and I want to get the font size that fits the best with my given width of 100 pixels.
I know I could calculate it in a loop (something like while(font.getSize() < panel.getWidth()
), but to be honest I don't find it very elegant.
You can get the rendered width and height of a string using the FontMetrics class (be sure to enable fractional font metrics in the Graphics2D instance to avoid rounding errors):
Graphics2D g = ...;
g.setRenderingHint(
RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
Font font = Font.decode("Times New Roman");
String text = "Foo";
Rectangle2D r2d = g.getFontMetrics(font).getStringBounds(text, g);
Now, when you have the width of the text using a font with the default (or actually any) size, you can scale the font, so that the text will fit within a specified width, e.g. 100px:
font = font.deriveFont((float)(font.getSize2D() * 100/r2d.getWidth()));
Similarly, you may have to limit the font size, so that you don't exceed the available panel height.
To improve the appearance of the rendered text, you should also consider enabling antialiasing for text rendering and/or kerning support in the font:
g.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Map<TextAttribute, Object> atts = new HashMap<TextAttribute, Object>();
atts.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
font = font.deriveFont(atts);
这篇关于从宽度的Java字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!