我需要在图像上(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
Run Code Online (Sandbox Code Playgroud)
它很好,但它不会自动打破线条(自动换行)以使所有文本适合我定义的区域(800x600).
我究竟做错了什么?
谢谢你的帮助:)
Dra*_*kin 11
在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
Run Code Online (Sandbox Code Playgroud)
我还有另一个功能,通过添加新行来转换文本以适应指定的宽度
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2279 次 |
| 最近记录: |