VisezTrance

  • March 2, 2011 11:14 PM

    Texts over multiple lines with RMagick

    By Daniel
    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.

    Tags:

    • RMagick,
    • ruby
  • Monthly Archives

    • October 2013 (2)
    • May 2012 (1)
    • October 2011 (1)
    • September 2011 (2)
    • March 2011 (3)
    • February 2011 (1)
    • January 2011 (1)
    • September 2010 (1)
    • August 2010 (1)
    • June 2010 (1)
    • April 2010 (1)
    • December 2009 (1)
    • October 2009 (1)
    • September 2009 (1)
    • August 2009 (1)
    • July 2009 (2)
    • April 2009 (2)
    • February 2009 (1)
    • January 2009 (2)
    • December 2008 (1)
    • October 2008 (1)
  • Pages

    • About / Contact

2008, © Daniel Mircea