在RMagick中创建两种颜色的标题

时间:2012-11-12 17:31:41

标签: ruby imagemagick 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

任何想法?还是要读些什么,这样我才能做到这一点?

谢谢!

1 个答案:

答案 0 :(得分: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)