如何使用 RMagick 和自动换行在图像上呈现文本? [英] How to render text on image with RMagick and Word wrap?

查看:59
本文介绍了如何使用 RMagick 和自动换行在图像上呈现文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to render some text (unicode, helvetica, white, 22px, bold) on a image (1024x768).

这是我目前的代码:

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).

Its all fine but its not automatically breaking the lines (Word wrap) to fit all the text into my defined area ( 800x600 ).

我做错了什么?

感谢您的帮助:)

推荐答案

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

On the Draw.annotate method the width parameter doesn't seem to have an effect on the rendering text.

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

I have faced the same problem and I developed this functions to fit the text to a specified width by adding new lines.

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

I have a function to check if a text fit a specified width when drawed on image

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

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

And I have another function to transform the text to fit in the specified width by adding new lines

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

这篇关于如何使用 RMagick 和自动换行在图像上呈现文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆