0

RMagick 应该在图像上自动换行文本并为该文本添加断线。这是我这样做的代码:

def word_wrap(text, columns = 80)
text.split("\n").collect do |line|
  line.length > columns ? line.gsub(/(.{1, #{columns}})(\s+|$)/, "\\1\n").strip : line
end * "\n"
end

process :caption

def caption
  manipulate! do |source|

    txt = Magick::Draw.new
    txt.font_family = "Impact"
    txt.fill = "#ffffff"


    position = 80
    top_caption = model.top_caption
    word_wrap(top_caption, 90).split("\n").each do |row|
      source.annotate(txt, 0, 0, 0, position +=20, row)
    end
  end
end
end

我得到这个错误:

(asasfasf 是我在文本中写的文本 - top_caption)

 NoMethodError in AnswersController#create

 undefined method `write' for ["asasfasf"]:Array

 app/uploaders/answer_uploader.rb:53:in `caption'
 app/controllers/answers_controller.rb:11:in `create'

创建动作:

def create
    @answer = Answer.new(params[:answer])
    @answer.user_id = current_user.id
    @answer.picture_id = daily_picture.id
    @answer.answer = daily_picture.image
    if @answer.save
      redirect_to root_path
    end
  end

和控制台中的错误:

Completed 500 Internal Server Error in 69ms

NoMethodError (undefined method `annotate' for #<Picture:0x007ffd2f578c88>):
  app/uploaders/answer_uploader.rb:64:in `block (2 levels) in caption'
  app/uploaders/answer_uploader.rb:63:in `each'
  app/uploaders/answer_uploader.rb:63:in `block in caption'
  app/uploaders/answer_uploader.rb:53:in `caption'
  app/controllers/answers_controller.rb:11:in `create'

代码中的问题在哪里?

谢谢!

4

1 回答 1

0

要自动换行,您需要使用标题:

phrase = 'Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam.'
BACKGROUND_PATH = Rails.root.join('image_dir', 'background.jpg')    
background = Magick::Image.read(BACKGROUND_PATH).first
image = Magick::Image.read("caption:#{my_text}") do
  # puts self.methods
  self.size = '500x' #Text box size
  self.background_color = 'none' #transparent
  self.pointsize = 30 # font size
  self.font = 'Tahoma' #font family
  self.fill = 'gray' #font color
  self.gravity = Magick::CenterGravity #Text orientation
end.first
background.composite!(image, Magick::NorthEastGravity, 20, 40, Magick::OverCompositeOp)
background.write('/image/path/image_name.jpg')
于 2019-09-04T01:42:03.870 回答