我需要在数据库中存储文本片段以及将文本包裹在浏览器屏幕中的图层的大小(我无法在客户端构建图层 - 这是项目的要求)。整段文本必须正确适合方形图层。用户将能够从一小组选项中使用不同的字体大小和字体系列,我们将在计算时知道选择。
现在,我根据每个字符大小是其字体大小像素高度和字体大小宽度的 50% 的理论来计算图层体积。使用 50% 的值,我得到了平均情况的最佳近似值,但这仍然不是一个好的解决方案,因为它会剪切文本片段或在末尾留下太多空白。对于一些较宽的字体类型来说情况更糟。
关于如何解决这个问题有什么想法吗?
I need to store in a database pieces of text and the size of the layer that will wrap the text in the browser screen (I cannot build the layer in the client side - it is a requirement of the project). The whole piece of text must fit into the square layer properly. Users will be able to use different font size and font families from a small group of options and we'll know the selection at the time of computation.
Right now, I compute the layer volume based in the theory that every character size is its font-size pixels height and 50% of the font-size width. With the 50% value, I got the best approximation for the average cases, but it is still not a good solution because it cuts pieces of text or leaves too much blank space at the end. And it's even worst with some wider font-types.
Any idea on how to approach this problem?
发布评论
评论(2)
考虑到用户在浏览器中覆盖字体选择是多么容易,这充其量只是“最佳猜测”尝试,但您可以使用 GD 绘制文本,然后使用 imagettfbbox()。
但这只支持简单的文本,所以如果你正在用粗体/斜体、可变大小等做“复杂”的事情,那么你在很大程度上是SOL。
Given how easy it is for users to override font choices in the browser, at best this would only be a "best guess" attempt, but you could use GD to draw the text and then compute a bounding box for it using imagettfbbox().
But this only supports simple text, so if you're doing "complicated" stuff with boldface/italics, variable sizes, etc.. then you're SOL for the most part.
考虑到要求,100% 保证做到这一点的唯一方法是:
在服务器上渲染图像——这可以是普通图像、矢量格式(如 SVG),甚至是(更极端)到 Flash - 并且以某种形式使用客户端生成的输出,以保证精确渲染,因为任何 CSS 渲染/本地字体问题都可能与服务器生成的值不同,并且因此是不可靠的!
因此,盒子的确切尺寸是独立于本地字体渲染问题而已知的,因为它们仅取决于服务器“视图”。
快乐编码。
Given the requirements, the only way to do this 100% guaranteed is to:
Render the image on the server -- this can be to a normal image, to a vector format such as SVG, or even (more extreme) to Flash -- and use the generated output on the client in some form which guarantees precise rendering as any CSS rendering/local-font issues may differ from the server-generated values and is thus unreliable!
The exact dimensions of the box are thus known independent upon local font rendering issues as they depend only upon the servers "view".
Happy coding.