像下面这样的东西应该适合你。(请注意,这只是为了向您展示过程;我不建议将这样的代码投入生产。这是乞求放在自己的类中编辑:见下文):
draw = Magick::Draw.new
设置绘图对象上的所有文本属性:
draw.pointsize = 20
draw.fill = '#000000'
draw.gravity = Magick::NorthGravity
draw.font_weight = 100
draw.font_family = "Arial"
draw.font_style = Magick::NormalStyle
获取您的图像对象(这只是一个新的空白图像):
image = Magick::Image.new(300,200)
设置字符串并使用get_type_metrics测量它们:
black_text = "This "
red_text = "RED"
remainder = " has to be in red"
black_text_metrics = draw.get_type_metrics(black_text)
red_text_metrics = draw.get_type_metrics(red_text)
remainder_metrics = draw.get_type_metrics(remainder)
用黑色文本注释:
draw.annotate(image,
black_text_metrics.width,
black_text_metrics.height,
10,10,black_text)
将颜色更改为红色并添加红色文本:
draw.fill = "#ff0000"
draw.annotate(image,
red_text_metrics.width,
red_text_metrics.height,
10 + black_text_metrics.width, # x value set to the initial offset plus the width of the black text
10, red_text)
将颜色改回黑色并添加文本的其余部分:
draw.fill = "#000000"
draw.annotate(image,
remainder_metrics.width,
remainder_metrics.height,
10 + black_text_metrics.width + red_text_metrics.width,
10, remainder)
编辑:这可能会让您了解如何更好地构建它:
TextFragment = Struct.new(:string, :color)
class Annotator
attr_reader :text_fragments
attr_accessor :current_color
def initialize(color = nil)
@current_color = color || "#000000"
@text_fragments = []
end
def add_string(string, color = nil)
text_fragments << TextFragment.new(string, color || current_color)
end
end
class Magick::Draw
def annotate_multiple(image, annotator, x, y)
annotator.text_fragments.each do |fragment|
metrics = get_type_metrics(fragment.string)
self.fill = fragment.color
annotate(image, metrics.width, metrics.height, x, y, fragment.string)
x += metrics.width
end
end
end
和一个用法示例:
image = Magick::Image.new(300,200)
draw = Magic::Draw.new
draw.pointsize = 24
draw.font_family = "Arial"
draw.gravity = Magick::NorthGravity
annotator = Annotator.new #using the default color (black)
annotator.add_string "Hello "
annotator.add_string "World", "#ff0000"
annotator.add_string "!"
draw.annotate_multiple(image, annotator, 10, 10)