Algorithm for estimating text width based on contents

前端 未结 8 2147
傲寒
傲寒 2021-02-08 09:11

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?

For example, I\'d

相关标签:
8条回答
  • 2021-02-08 09:53

    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

    0 讨论(0)
  • 2021-02-08 09:53

    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.

    0 讨论(0)
提交回复
热议问题