6

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.

Unfortunately, I do not know how to predict the pixel extents of a specific string of text in SVG. I can choose what font I use (but I don't think monospace will be acceptable) and what font size I'm using.

How would I go about using python to predict the extents of the SVG text so I can generate an appropriately sized rectangle?

Mutant Bob
  • 3,121
  • 2
  • 27
  • 52

1 Answers1

4

I think things would get messy if you did this in Python. Probably the least stressful approach would be to install FreeType and use it to calculate the text dimensions for you. 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.

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>
Community
  • 1
  • 1
r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • That is a very useful technique. While it may form the basis for my final solution, I have not yet figured out how to make the box form a fixed (for example 10px) margin around the text. I'll continue experimenting. – Mutant Bob Feb 07 '16 at 14:45
  • I went with your "large hammer" suggestion and installed freetype-py. I can run that from within blender to write out PNGs for use in VSE image strips. It doesn't answer this specific question, but it accomlishes the mission that created the question. – Mutant Bob Feb 11 '16 at 21:25
  • This answer making use of the python PIL library appears relevant: https://stackoverflow.com/questions/35771863/how-to-calculate-length-of-string-in-pixels-for-specific-font-and-size – Thomas Kimber Feb 01 '22 at 14:01