2012-11-12 60 views
3

用兩種顏色創建一個頭銜,我需要創建使用兩種顏色的圖片的標題,所有的話都是黑色的,除了一個其他顏色...在RMagick

我一直在閱讀的文檔RMagick我找不到這樣做的方法...我現在用來創建文本的是:

txt_name = Draw.new 
image.annotate(txt_name, 0,0,0,0, "This RED has to be in red") do 
    self.gravity = Magick::NorthGravity 
    self.pointsize = 20 
    self.fill = '#000000' 
    txt_name.font_weight = 100 
    self.font_family = 'Arial' 
end 

任何想法?或者有東西要閱讀,所以我可以做這個工作?

謝謝!

回答

4

像下面這樣的東西應該適合你。 (請注意,這只是向你展示的過程中,我不會建議把這樣的代碼投入生產這乞討被放在自己的類編輯:見下文):

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) 
+0

真棒的感謝! – Andres