如何在 Java2D 中剪辑字符串并在最后添加 ...?
我正在尝试在 Java Swing 应用程序中打印发票。我通过扩展 Printable
并实现方法 public int print(Graphics g, PageFormat pf, int page)
来实现这一点。
我想在列中绘制字符串,当字符串太长时,我想剪掉它并让它以“...”结尾。如何测量绳子并将其夹在正确的位置?
我的一些代码:
Font headline = new Font("Times New Roman", Font.BOLD, 14);
g2d.setFont(headline);
FontMetrics metrics = g2d.getFontMetrics(headline);
g2d.drawString(myString, 0, 20);
即如何将 myString
限制为最大 120px?
我可以使用metrics.stringWidth(myString),但我没有得到必须剪辑字符串的位置。
预期结果可能是:
A longer string that exc...
A shorter string.
Another long string, but OK
I'm trying to print Invoices in a Java Swing applications. I do that by extending Printable
and implement the method public int print(Graphics g, PageFormat pf, int page)
.
I would like to draw strings in columns, and when the string is to long I want to clip it and let it end with "...". How can I measure the string and clip it at the right position?
Some of my code:
Font headline = new Font("Times New Roman", Font.BOLD, 14);
g2d.setFont(headline);
FontMetrics metrics = g2d.getFontMetrics(headline);
g2d.drawString(myString, 0, 20);
I.e How can I limit myString
to be max 120px?
I could use metrics.stringWidth(myString)
, but I don't get the position where I have to clip the string.
Expected results could be:
A longer string that exc...
A shorter string.
Another long string, but OK
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一旦您知道需要剪切字符串,您就可以使用二分搜索来查看可以显示多少个字符,包括省略号后缀。
这类似于您尝试 N-1 个字符、N-2、N-3 等,直到找到适合允许空间的子字符串 +“...”。但您不是线性迭代,而是使用二分搜索来查找尝试次数较少的字符数。
Once you know that the string needs to be clipped, you can use a binary search to see how many characters you can display, including the elipsis suffix.
This is similar to if you were to try N-1 chars, N-2, N-3 etc.. until you found a substring + "..." that fits within the allowed space. But rather than iterate linearly, you use binary search to find the number of characters with fewer attempts.
您可以通过将 stringWidth 除以字符数来获得每个字符的平均宽度,从而获得良好的估计。然后,您可以获取剪辑距离,看看可以容纳多少个字符。将子字符串从开头到几乎那个距离(... 减去两个或三个)并将您的 ... 放在末尾。
验证新字符串是否会被剪辑 - 如果是,请根据需要进行一些调整。毕竟,如果您有 WWWWWWWWiiiiii,您可能需要对其进行调整。但总而言之,这种方法会非常快。
You can get a good estimate by taking the stringWidth divided by the number of characters to get the average width per character. Then you can take the clip distance to see how many characters you can fit in. Take the substring from the start to almost that distance (minus two or three for the ...) and put your ... on the end.
Verify the new string doesn't clip - if it does, make some adjustments as necessary. After all if you have WWWWWWWWiiiiii, you'll probably need to adjust that. But all in all, this approach will be pretty fast.