Home Ask Login Register

Developers Planet

Your answer is one click away!

Mutant Bob February 2016

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.

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?

Answers


squeamish ossifrage February 2016

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>

Post Status

Asked in February 2016
Viewed 3,732 times
Voted 6
Answered 1 times

Search




Leave an answer


Quote of the day: live life