3

我需要使用两种颜色为图片创建标题,所有单词都是黑色的,除了一个是其他颜色的......

我一直在阅读 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

1 回答 1

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)
于 2012-11-12T19:13:36.313 回答