如何确定图形字符串的长度?
我正在从 Excel 文档创建图形时间线,并且需要在该事件的标记旁边添加事件名称的小标签。其中一些很简单并且右对齐,但其他一些则左对齐,我需要计算出它们的宽度,以便我可以正确地偏移它们。
window.drawString("7/4-Fourth of July",horizontalIndex-Offset,verticalIndex);
目前,我使用字体大小 10 和 32 的平均值来平均像素宽度,但这并不能真正解决问题。有人可以帮我获得确切的偏移量吗?
I'm creating a graphical timeline out of an excel document and I need to have small tags of the name of the event next to the marker for that event. Some of these are easy and are right justified but others are left justified and I need to figure out their width so that I can properly offset them.
window.drawString("7/4-Fourth of July",horizontalIndex-Offset,verticalIndex);
Currently I'm averaging the pixel width using an average of both font sizes 10 and 32, but this doesn't really cut it. Can someone help me get the exact offset?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该线程解释了如何执行此操作:
计算 Java 中字符串的显示宽度
应该首先获取字体指标,然后询问指标某个字符串的宽度。
This thread explains how to do it:
Calculate the display width of a string in Java
You should first get the font metrics, and then ask the metrics how wide a certain string is.
从 java.awt.Graphics 对象中,您可以调用 getFontMetrics。 FontMetrics 对象有一个 getStringBounds 方法可以满足您的需要。
这是 文档
from a java.awt.Graphics object, you can call getFontMetrics. the FontMetrics object has a getStringBounds method that does what you need.
here's the documentation
另一个不错的选择是 SwingUtilities#computeStringWidth(FontMetrics fm, String str)
and another good alternative is SwingUtilities#computeStringWidth(FontMetrics fm, String str)
作为(阅读:我的;-)一般规则,永远不要使用图形级drawString方法。相反,使用 JLabel/CellRendererPane 对将文本“标记”到任何组件上。
优点
As a (read: my ;-) general rule, never use the Graphics-level drawString methods. Instead, use a JLabel/CellRendererPane pair to "stamp" the text onto whatever component.
The advantages
TextLayout
此处显示的 a> 是另一种替代方案。TextLayout
, shown here, is another alternative.