[英]using python, how do I predict the pixel width of text in an SVG?
I am using python to generate an SVG with text that can vary, and I'd like to put a translucent rectangle behind it to guarantee some contrast when it is overlayed on another graphical element later on. 我正在使用python来生成一个带有可以变化的文本的SVG,并且我想在它后面放一个半透明的矩形以保证稍后在其他图形元素上重叠时的一些对比度。
Unfortunately, I do not know how to predict the pixel extents of a specific string of text in SVG. 不幸的是,我不知道如何预测SVG中特定文本字符串的像素范围。 I can choose what font I use (but I don't think monospace will be acceptable) and what font size I'm using. 我可以选择我使用的字体(但我不认为monospace是可以接受的)以及我正在使用的字体大小。
How would I go about using python to predict the extents of the SVG text so I can generate an appropriately sized rectangle? 我将如何使用python预测SVG文本的范围,以便生成适当大小的矩形?
I think things would get messy if you did this in Python. 我觉得如果你用Python做这件事会让事情变得混乱。 Probably the least stressful approach would be to install FreeType and use it to calculate the text dimensions for you. 可能压力最小的方法可能是安装FreeType并使用它来为您计算文本尺寸。 But that's a very large hammer for quite a small nut. 但对于相当小的坚果来说,这是一个非常大的锤子。
This answer shows an easier approach — use an SVG filter to apply a background directly to the text without having to resize anything. 这个答案显示了一种更简单的方法 - 使用SVG过滤器将背景直接应用于文本,而无需调整任何大小。
You can use this method with translucent backgrounds too: 您也可以将此方法用于半透明背景:
<svg width="360" height="100" viewBox="0 0 360 100"> <defs> <filter x="0" y="0" width="1" height="1" id="text-bg"> <feFlood flood-color="#ff0" flood-opacity="0.5" /> <feComposite in="SourceGraphic" /> </filter> </defs> <rect x="0" y="0" width="400" height="100" fill="#444" stroke="none" /> <path d="m0 10 40 80 40-80 40 80 40-80 40 80 40-80 40 80 40-80 40 80" stroke="#888" stroke-width="10" fill="none" /> <text font-family="Arial" font-weight="bold" filter="url(#text-bg)" x="180" y="50" font-size="20" fill="#000" text-anchor="middle"> Edit this text and reload the SVG </text> </svg>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.