I recently worked on a project that generated some custom images using RMagick. There were several texts involved with some spanning over multiple rows. While RMagick does provide a caption method that wraps the text, I found it rather limiting. So instead I used the more powerful annotate method which allowed me to set my own font and text position.
Having just a canvas (an RMagick image for background), I started by creating a new drawing object:
drawing = Magick::Draw.new
I then used a method for splitting the text into rows (stolen from a rails helper):
def word_wrap(text, columns = 80)
text.split("\n").collect do |line|
line.length > columns ? line.gsub(/(.{1,#{columns}})(\s+|$)/, "\\1\n").strip : line
end * "\n"
end
Writing the actual text was easier than I initially thought.
position = 80
word_wrap(my_long_text, 90).split(\n).each do |row|
drawing.annotate(canvas, 0, 0, 200, position += 20, row)
end
The text is being added at the 200, 100 coordinates, with a line height of 20. That's it.