Ruby/GD2: generate image that strictly fits a text

  • Thread starter Jonathan Métillon
  • Start date
J

Jonathan Métillon

Hi!

I'm trying to use GD2::Image and GD2::Font::TrueType to get an image to
fit a text string. I use the bounding_rectangle() method to extract the
bounding box (bbox).

My issue is that the image never really fits the text. It adds some
margins. Maybe I don't resize the image correctly according to the bbox
data? Here's my code:

text = 'some text'
image = Image.import('white.png') #this is 1x1 white image
image.draw do |pen|
pen.font = Font::TrueType['Arial_Bold.ttf', 10]
pen.color = image.palette.resolve Color[0, 0, 0]
bbox = pen.font.bounding_rectangle(text)
width = bbox[:lower_right][0].abs + bbox[:upper_left][0].abs
height = bbox[:lower_right][1].abs + bbox[:upper_left][1].abs
image.resize! width, height
pen.move 0, bbox[:upper_right][1].abs
pen.text text
end
image.export('new-image.png')

Is there something I can do so the image strictly fits the text, with no
margin?

Thank you!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top