2012-08-03 23 views
2

我需要在圖像(1024x768)上渲染一些文字(unicode,helvetica,white,22px,粗體)。如何在RMagick和Word換行的圖像上呈現文本?

這是我到目前爲止的代碼:

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 

其所有的罰款,但它不會自動斷行(自動換行),以適合所有文本到我的指定區域(800×600)。

我在做什麼錯?

感謝您的幫助:)

回答

8

在Draw.annotate方法寬度參數似乎並沒有對渲染文本的效果。

我遇到了同樣的問題,我開發了這個函數,通過添加新行來使文本適應指定的寬度。

我有一個函數來檢查文本符合指定的寬度上圖像

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 

drawed當我有另一種功能,通過添加新行

以變換文本以適應指定的寬度
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 
+0

謝謝!這項工作如預期的那樣,並且不需要重新實施就是一個巨大的節省時間的工具。 – Thierry 2014-12-29 14:25:38