Class | Fleximage::Operator::Text |
In: |
lib/fleximage/operator/text.rb
|
Parent: | Operator::Base |
Draw text on the image. Customize size, position, color, dropshadow, and font.
image.text(string_to_write, options = {})
Use the following keys in the options hash:
Example:
@photo.operate do |image| image.text('I like Cheese', :alignment => :top_left, :offset => '300x150', :antialias => true, :color => 'pink', :font_size => 24, :font => 'path/to/myfont.ttf', :rotate => -15, :shadow => { :blur => 1, :opacity => 0.5, } ) end
# File lib/fleximage/operator/text.rb, line 37 37: def operate(string_to_write, options = {}) 38: options = { 39: :alignment => :top_left, 40: :offset => '0x0', 41: :antialias => true, 42: :color => 'black', 43: :font_size => '12', 44: :font => nil, 45: :text_align => :left, 46: :rotate => 0, 47: :shadow => nil, 48: }.merge(options) 49: options[:offset] = size_to_xy(options[:offset]) 50: 51: # prepare drawing surface 52: text = Magick::Draw.new 53: text.gravity = GRAVITIES[options[:alignment]] 54: text.fill = options[:color] 55: text.text_antialias = options[:antialias] 56: text.pointsize = options[:font_size].to_i 57: text.rotation = options[:rotate] 58: 59: # assign font path with to rails root unless the path is absolute 60: if options[:font] 61: font = options[:font] 62: font = "#{RAILS_ROOT}/#{font}" unless font =~ %r{^(~?|[A-Za-z]:)/} 63: text.font = font 64: end 65: 66: # draw text on transparent image 67: temp_image = Magick::Image.new(@image.columns, @image.rows) { self.background_color = 'none' } 68: temp_image = temp_image.annotate(text, 0, 0, options[:offset][0], options[:offset][1], string_to_write) 69: 70: # add drop shadow to text image 71: if options[:shadow] 72: shadow_args = [2, 2, 1, 1] 73: if options[:shadow].is_a?(Hash) 74: #shadow_args[0], shadow_args[1] = size_to_xy(options[:shadow][:offset]) if options[:shadow][:offset] 75: shadow_args[2] = options[:shadow][:blur] if options[:shadow][:blur] 76: shadow_args[3] = options[:shadow][:opacity] if options[:shadow][:opacity] 77: end 78: shadow = temp_image.shadow(*shadow_args) 79: temp_image = shadow.composite(temp_image, 0, 0, symbol_to_blending_mode(:over)) 80: end 81: 82: # composite text on original image 83: @image.composite!(temp_image, 0, 0, symbol_to_blending_mode(:over)) 84: end