使用Compass生成精灵图,智能布局和间距。

10
我正在尝试使用SASS Compress生成一些精灵,我希望像文档http://compass-style.org/help/tutorials/spriting/sprite-layouts/中所示,对精灵文件应用智能布局。
这很好用:
$sprites: sprite-map("sprite/*.png", $spacing: 20px);

但是当我添加布局后,它就会出现问题;没有间距,也没有智能布局:

$sprites: sprite-map("sprite/*.png", $layout: smart, $spacing: 

我如何将智能布局应用于生成的精灵?

更新 经过一段时间的尝试,我终于做到了:

$sprite-spacing: 20px;
$sprite-layout: smart;
@import "sprite/*.png";
@include all-sprite-sprites;

但现在我无法让间距起作用。精灵很聪明,但没有间距。


1
当使用智能布局时,无法设置间距。 - agustibr
3个回答

13

智能布局无法支持间距的原因在于它根本不支持间距。间距只对水平和垂直布局有任何影响。

话虽如此,如果您愿意修补指南针代码,就可以自己添加支持。您需要替换layout_methods.rb文件中的calculate_smart_positions方法,该文件位于lib/compass/sass_extensions/sprites/layout_methods.rb(相对于指南针安装目录)。

更新后的方法应该是这样的:

def calculate_smart_positions
  fitter = ::Compass::SassExtensions::Sprites::RowFitter.new(@images)
  current_y = 0                   
  width = 0
  height = 0
  last_row_spacing = 9999
  fitter.fit!.each do |row|
    current_x = 0                  
    row_height = 0
    row.images.each_with_index do |image, index|
      extra_y = [image.spacing - last_row_spacing,0].max
      if index > 0
        last_image = row.images[index-1]
        current_x += [image.spacing, last_image.spacing].max
      end
      image.left = current_x
      image.top = current_y + extra_y
      current_x += image.width
      width = [width, current_x].max
      row_height = [row_height, extra_y+image.height+image.spacing].max
    end
    current_y += row.height
    height = [height,current_y].max
    last_row_spacing = row_height - row.height
    current_y += last_row_spacing
  end
  @width = width
  @height = height
end
请注意,这有时可能无法产生最佳的布局,因为它仅在行适配算法已经决定了如何将精灵分成行之后应用间距。不过,对于大多数情况来说,它应该足够好了。
我还要提到的是,我基本上没有使用Ruby编程的经验,所以这段代码可能写得非常糟糕。不过,它似乎能够正常工作。

它运行得非常完美,但我正在寻找一种解决方案,使我不需要自己更改指南针文件。我不是这个项目上唯一的开发人员。Ruby代码做得很好! - Tommy Bjerregaard
1
@TommySorensen 我完全打算将其作为补丁提交给Compass项目 - 我只是在等待一些反馈,以确定它是否有效。他们是否愿意接受当前形式的代码是另一个问题,但我认为至少它比其他拉取请求更好。 - James Holderness
好的,很棒的想法。这段代码在当前形式下对我来说是可以工作的,没有问题。现在我不必等待拉取请求了。 - Tommy Bjerregaard

1

拉取请求是我想要的,现在我只能等待它。 - Tommy Bjerregaard
#718 已经合并到 Compass 了吗?或者你知道它的状态吗? - Tommy Bjerregaard
不,这个还没有合并。它是针对稳定版本创建的,需要重新基于主分支进行修改,因为内部API发生了一些变化。而且存在一些代码质量问题。http://git.io/wrUNLg - agustibr

0

它支持每个图像之间的垂直和水平对齐以及填充吗? - Tommy Bjerregaard
如果你将精灵布局设置为垂直或水平,它将支持间距。如果你保持智能布局,它将不支持图像之间的任何间距,这是指南针配置,无法更改。 - paul.g

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接