如何使用RMagick和Word换行在图像上渲染文本?

时间:2012-08-03 01:54:12

标签: ruby rmagick

我需要在图像上(1024x768)渲染一些文本(unicode,helvetica,白色,22px,粗体)。

到目前为止,这是我的代码:

img = Magick::ImageList.new("my_bg_img.jpg")
txt = Magick::Draw.new

img.annotate(txt, 800, 600, 0, 0, "my super long text that needs to be auto line breaked and cropped") {
      txt.gravity = Magick::NorthGravity
      txt.pointsize = 22
      txt.fill = "#ffffff"
      txt.font_family = 'helvetica'
      txt.font_weight = Magick::BoldWeight
}

img.format = "jpeg"

return img.to_blob

它很好但它不会自动断行(自动换行)以使所有文本适合我定义的区域(800x600)。

我做错了什么?

感谢您的帮助:)

3 个答案:

答案 0 :(得分:9)

在Draw.annotate方法中,width参数似乎对渲染文本没有影响。

我遇到了同样的问题,我开发了这个函数,通过添加新行使文本适应指定的宽度。

我有一个函数来检查在图像上绘制时文本是否适合指定的宽度

def text_fit?(text, width)
  tmp_image = Image.new(width, 500)
  drawing = Draw.new
  drawing.annotate(tmp_image, 0, 0, 0, 0, text) { |txt|
    txt.gravity = Magick::NorthGravity
    txt.pointsize = 22
    txt.fill = "#ffffff"
    txt.font_family = 'helvetica'
    txt.font_weight = Magick::BoldWeight
  }
  metrics = drawing.get_multiline_type_metrics(tmp_image, text)
  (metrics.width < width)
end

我还有另一个函数可以通过添加新行来转换文本以适应指定的宽度

def fit_text(text, width)
  separator = ' '
  line = ''

  if not text_fit?(text, width) and text.include? separator
    i = 0
    text.split(separator).each do |word|
      if i == 0
        tmp_line = line + word
      else
        tmp_line = line + separator + word
      end

      if text_fit?(tmp_line, width)
        unless i == 0
          line += separator
        end
        line += word
      else
        unless i == 0
          line +=  '\n'
        end
        line += word
      end
      i += 1
    end
    text = line
  end
  text
end

答案 1 :(得分:0)

尝试一下:

phrase = "my super long text that needs to be auto line breaked and cropped"
background = Magick::Image.read('my_bg_img.jpg').first
image = Magick::Image.read("caption:#{my_text}") do
  self.size = '800x600' #Text box size
  self.background_color = 'none' #transparent
  self.pointsize = 22 # font size
  self.font = 'Helvetica' #font family
  self.fill = 'gray' #font color
  self.gravity = Magick::CenterGravity #Text orientation
end.first
background.composite!(image, Magick::NorthEastGravity, 20, 40, Magick::OverCompositeOp)
background.format = "jpeg"
return background.to_blob

答案 2 :(得分:-2)

找到一些可以解决这个问题的代码here

相关问题