基于内容的算法估算文字宽度宽度、算法、文字、内容

2023-09-11 03:18:44 作者:メ噯de檤‰

这是一个长镜头,但没有人知道的算法基于内容评估和分类的文字宽度(对于可变宽度字体)?

This is a long shot, but does anyone know of an algorithm for estimating and categorising text width (for a variable width font) based on its contents?

例如,我想知道的 iiiiiiii 的是不一样宽的 ABCDEFGH 的,这又是不一样宽的 WWWWWWWW ,即使所有的三根弦的长度为八个字符。

For example, I'd like to know that iiiiiiii is not as wide as abcdefgh, which in turn is not as wide as WWWWWWWW, even though all three strings are eight characters in length.

这其实是建立一些智慧转化为字符串截断的方法,这在目前是正确截断视觉宽字符串的尝试,但也不必要地截断视觉狭窄的字符串,因为这两个字符串包含相同的字符数。这可能足以让算法对输入的字符串作为分类的窄的正常或宽的,然后截断为合适。

This is actually an attempt to build some smarts into a string truncation method, which at the moment is correctly truncating a visually wide string, but is also unnecessarily truncating a visually narrow string, because both strings contain the same number of characters. It's probably sufficient for the algorithm to categorise the input string as narrow, normal or wide and then truncate as appropriate.

这个问题是不是真的特定于语言的,但是如果有一个算法,然后我会在Java中实现它。这是一个Web应用程序。我知道,有对答案,这样处理使用JavaScript,得到了含有 DIV 元素的宽度这个问题,但我想,如果一个服务器端解决方案可能的。

This question isn't really language-specific, but if there is an algorithm then I'll implement it in Java. This is for a web application. I'm aware that there are answers on SO that deal with this problem using JavaScript to obtain the width of a containing div element, but I wondered if a server-side solution is possible.

推荐答案

大多数GUI框架提供了一些方法来计算给定输出设备,文本度量的字体。

Most GUI frameworks provide some way to calculate text metrics for fonts on given output devices.

使用 java.awt.FontMetrics中,例如,我相信你可以做到这一点:

Using java.awt.FontMetrics, for example, I believe you can do this:

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics; 

public int measureText(Graphics g, String text) {
   g.setFont(new Font("TimesRoman", Font.PLAIN, 12));
   FontMetrics metrics = g.getFontMetrics();

   return metrics.stringWidth(text);
}

没测试过,但你的想法。

Not tested, but you get the idea.

在.net中,您可以使用 Graphics.MeasureString 方法。在C#:

Under .Net you can use the Graphics.MeasureString method. In C#:

private void MeasureStringMin(PaintEventArgs e)
{

    // Set up string.
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);

    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}