像下面這樣的東西應該適合你。 (請注意,這只是向你展示的過程中,我不會建議把這樣的代碼投入生產這乞討被放在自己的類編輯:見下文):
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)
真棒的感謝! – Andres