문제

이것은 긴 샷이지만, 내용을 기반으로 텍스트 너비 (가변 너비 글꼴의 경우)를 추정하고 분류하기위한 알고리즘을 아는 사람이 있습니까?

예를 들어, 알고 싶습니다 iiiiiiii 넓지 않습니다 Abcdefgh, 그것은 차례로 넓지 않습니다 wwwwwww, 세 문자열은 모두 8 자입니다.

이것은 실제로 일부 스마트를 문자열 자르기 방법으로 구축하려는 시도이며, 현재 시각적으로 넓은 문자열을 올바르게 잘라 내고 있지만 두 줄에 동일한 수의 문자가 포함되어 있기 때문에 시각적으로 좁은 문자열을 불필요하게 잘라냅니다. 알고리즘이 입력 문자열을 좁은, 정상 또는 넓은 그런 다음 적절하게 자릅니다.

이 질문은 실제로 언어 별은 아니지만 알고리즘이 있다면 Java로 구현하겠습니다. 이것은 웹 응용 프로그램을위한 것입니다. javaScript를 사용 하여이 문제를 처리하여 포함 된 A의 너비를 얻을 수있는 답이 있음을 알고 있습니다. div 요소이지만 서버 측 솔루션이 가능한지 궁금했습니다.

도움이 되었습니까?

해결책

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

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.


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));
}

다른 팁

This worked for me:

AffineTransform af = new AffineTransform();     
FontRenderContext fr = new FontRenderContext(af,true,true);     
Font f = new Font("Arial", 0, 10); // use exact font
double width= f.getStringBounds("my string", fr).getWidth();      

For a web application, you cannot (really) get a proper estimation. Different fonts have different widths, so that this not only depends on the client (browser) and its zoom and DPI settings, but also on the fonts present on that machine (and operating system) or their substitutions.

If you need exact measuring, create a graphic (bitmap, SVG, or even some PDF or whatever) which will be layouted and rendered on the server and not on the client.

There is no reliable server side solution for calculating width of text. (outside of creating an image of the text and probably SVG)

If you try a tool out like browser-shots and run it against relatively basic pages, you'll immediately see why. It's hard to predict how wide even the most mundane examples will turn out, much less if a user decides to zoom in the browser etc...

It's not stated precisely you might want to truncate the string (it might be helpful in giving potential solutions), but a common one is because you want to cut off the text at some point and provide an ellipse.

This can be done reliably on many browser platforms by using a css property, and NO javascript:

http://www.jide.fr/emulate-text-overflowellipsis-in-firefox-with-css

You really have no way of knowing what browser, font settings, screen size etc the client is using. (OK, sometimes the request headers provide an indication, but really nothing consistent or reliable.)

So, I would:

  • display some sample text in Internet Explorer with default settings on a screen/window size of 1024x768 (this is generally the most common size)
  • take an average characters/line with this configuration and use that for your estimate.

I've generally found this "good enough", for example, for estimating the number of lines that some text will take up on a browser, in order to estimate how many adverts to show next to the text.

If it was really really crucial to you, then I can imagine a convoluted scheme whereby you initially send some Javascript to the client, which then takes a measurement and sends it back to your server, and you then use this information for future pages for that client. I can't imagine it's usually worth the effort, though.

I think you should choose one of these solutions:

  • Exact solution: Sum up the width for every character in the string (most APIs will give you this information)
  • Quick estimate: Either take the maximum or the minimum width and multiply it with the numbers of characters.

Of course some mixed estimate is possible, but I think this is too much effort in the wrong direction.

For a nice* client-side solution, you could try a hybrid CSS-and-Javascript approach as suggested by RichieHindle's answer to my question.

Given that you don't know what font the user will see the page in (they can always override your selection, Ctrl-+ the page, etc), the "right" place to do this is on the browser... although browsers don't make it easy!

* when I say "nice", I mean "probably nice but I haven't actually tried it yet".

This is actually an attempt to build some smarts into a string truncation method [...]

Is it really worth the effort? We had this exact problem. And this was across languages. The fix was to leave it as-is. The complexity of keeping this intelligence up increases rapidly (and probably exponentially) with every language that you add support for. Hence our decision.

[...] an algorithm for estimating and categorising text width (for a variable width font) based on its contents?

Most font-libraries will give you this information. But this is pretty low-level stuff. The basic idea is to pass in a string and get back the width in points.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top