Dica rápida #4 - Image replacement com Rails e RMagick
12 de February de 2009 - 21:37
Se você quer estilizar seus textos com uma fonte diferente, experimente fazer image replacement com um helper que irá gerar a imagem
automaticamente. Adicione o método abaixo ao arquivo app/helpers/application_helper.rb.
def title_tag(text) hash = Digest::MD5.hexdigest(text)[0,10] relative_name = "titles/#{hash}.png" full_path = "#{Rails.root}/public/images/#{relative_name}"
unless File.file?(full_path) image = Magick::Image.new(500, 30) image.format = "PNG"
title = Magick::Draw.new
title.annotate(image, 500, 30, 0, 0, text) do self.fill = "#333" self.font = Rails.root + "/fonts/Clarenton LT Bold.ttf" self.font_family = "Clarenton LT Bold" self.font_weight = Magick::BoldWeight self.gravity = Magick::NorthWestGravity self.pointsize = 24 end
image.write(full_path) end
url = image_path(relative_name) content_tag(:h2, text, :class => "ir", :style => "background-image: url(#{url});")
end Agora, basta você chamar o helper da seguinte maneira:
<%= title_tag "Easy image replacement" %> Uma imagem como está será gerada:

No HTML, o código gerado será esse:
<h2 class="ir" style="background-image: url(/images/titles/ad80520fd1.png?1234484835);"> Easy image replacement
</h2> Você também vai precisar do CSS:
.ir { background: transparent no-repeat; height: 30px; text-ident: -9999px; width: 500px;
} Lembre-se de alterar o helper, adicionando sua fonte, cor e tamanho.







Comentários (0)