Gem 推荐用 sprite-factory 这个组件整合图片

huacnlee · 2011年11月18日 · 最后由 wxianfeng 回复于 2012年02月04日 · 4285 次阅读

上次有提到过 css_sprite http://ruby-china.org/topics/46 不过最近我在 Rails 3.1 项目里面用 sprite-factory,确实很好用。

定义个 Rake 任务

require 'sprite_factory'

namespace :assets do
  desc 'recreate sprite images and css'
  task :resprite => :environment do 
    SpriteFactory.library = :rmagick
    SpriteFactory.csspath = "<%= asset_path 'sprites/$IMAGE' %>"
    dirs = Dir.glob("#{Rails.root}/app/assets/images/sprites/*/")
    dirs.each do |path|
      dir_name = path.split("/").last
      SpriteFactory.run!("app/assets/images/sprites/#{dir_name}", 
                          :output_style => "app/assets/stylesheets/sprites/#{dir_name}.scss.erb", 
                          :selector => ".#{dir_name}_")
    end
  end
end

然后将需要组合的小图片放到 /app/assets/images/sprites/ 目录下面,并搞个子文件夹,如:

/app/assets/images/sprites/ask/new.png
/app/assets/images/sprites/ask/edit.png
/app/assets/images/sprites/topic/reply.png
/app/assets/images/sprites/topic/delete.png

用 Rake 命令整合图片

$ rake assets:resprite

整合以后就会有个

/* /app/assets/stylesheets/sprites/ask.scss.erb */
.ask_new { width: 19px; height: 19px; background: url(<%= asset_path 'sprites/ask.png' %>) 0px 0px no-repeat; }
.ask_edit { width: 19px; height: 19px; background: url(<%= asset_path 'sprites/ask.png' %>) -19px 0px no-repeat; }

/* /app/assets/stylesheets/sprites/topic.scss.erb */
.topic_reply { width: 19px; height: 19px; background: url(<%= asset_path 'sprites/topic.png' %>) 0px 0px no-repeat; }
.topic_delete { width: 19px; height: 19px; background: url(<%= asset_path 'sprites/topic.png' %>) -19px 0px no-repeat; }

你只需要在 application.css 里面引用 sprites 目录就好了

/*
 *= require_tree ./sprites/
*/
.icon { display:inline-block; }

HTML 里面使用

<a href="#" class="icon ask_new"></a>
<a href="#" class="icon topic_delete"></a>

sprite-factory 项目地址: https://github.com/jakesgordon/sprite-factory

这个确实很赞

很赞,不用慢慢调整图片了

一直在用 gimp 自己处理 ...

需要 登录 后方可回复, 如果你还没有账号请 注册新账号