使用 python,如何预测 SVG 中文本的像素宽度?

Mut*_*Bob 6 python svg

我正在使用 python 生成一个 SVG,其中的文本可能会有所不同,并且我想在其后面放置一个半透明矩形,以保证稍后将其覆盖在另一个图形元素上时的对比度。

不幸的是,我不知道如何预测 SVG 中特定文本字符串的像素范围。我可以选择我使用的字体(但我认为等宽字体是不可接受的)以及我使用的字体大小。

我将如何使用 python 来预测 SVG 文本的范围,以便生成适当大小的矩形?

squ*_*age 4

我认为如果你用 Python 来做这件事,事情会变得混乱。也许压力最小的方法是安装FreeType并使用它来计算文本尺寸。但这对于相当小的螺母来说是一个非常大的锤子。

\n\n

这个答案显示了一种更简单的方法 \xe2\x80\x94 使用 SVG 过滤器将背景直接应用于文本,而无需调整任何内容的大小。

\n\n

您也可以在半透明背景上使用此方法:

\n\n

\r\n
\r\n
<svg width="360" height="100" viewBox="0 0 360 100">\r\n  <defs>\r\n    <filter x="0" y="0" width="1" height="1" id="text-bg">\r\n      <feFlood flood-color="#ff0" flood-opacity="0.5" />\r\n      <feComposite in="SourceGraphic" />\r\n    </filter>\r\n  </defs>\r\n  <rect x="0" y="0" width="400" height="100" fill="#444" stroke="none" />\r\n  <path d="m0 10 40 80 40-80 40 80 40-80 40 80 40-80 40 80 40-80 40 80"\r\n        stroke="#888" stroke-width="10" fill="none" />\r\n  <text font-family="Arial" font-weight="bold" filter="url(#text-bg)"\r\n        x="180" y="50" font-size="20" fill="#000" text-anchor="middle">\r\n    Edit this text and reload the SVG\r\n  </text>\r\n</svg>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n