lib/polymer/sprite.rb in polymer-1.0.0.beta.6 vs lib/polymer/sprite.rb in polymer-1.0.0.beta.7
- old
+ new
@@ -42,12 +42,14 @@
#
# @param [String, Polymer::Source] name
# The name of the source whose position is to be returned, or the
# Polymer::Source instance itself.
#
- # @return [Integer, Source]
+ # @return [Integer]
# The vertical position of the source image.
+ # @return [nil]
+ # nil is returned if no sprite identified by +name+ exists.
#
def position_of(name)
name = name.name if name.is_a?(Polymer::Source)
unless self.source(name)
@@ -62,11 +64,11 @@
# generating CSS), it works out faster to fetch each source height
# just once.
@positions = {}
@sources.inject(0) do |offset, src|
@positions[src.name] = offset
- offset + src.image.rows + @padding
+ offset + src.image.height + @padding
end
end
@positions[name]
end
@@ -103,37 +105,34 @@
Polymer can't save the #{@name} sprite in
`#{@save_path.dirname.to_s}' as it isn't writable.
ERROR
end
- list = Magick::ImageList.new
+ width, height = @sources.inject([1, 0]) do |dimensions, source|
+ # Determine the width of the sprite by finding the widest source.
+ source_width = source.image.width
+ dimensions[0] = source_width if source_width > dimensions[0]
- @sources.each do |source|
- list << source.image
+ # Determine the height of the sprite by summing the height of each
+ # source.
+ dimensions[1] += source.image.height
- if @padding and @padding > 0
- list << Magick::Image.new(1, @padding) do
- self.background_color = '#F000'
- end
- end
+ dimensions
end
- # RMagick uses instance_eval, @set isn't available in the block below.
- sources_length = @sources.length
+ if @padding and @padding > 0
+ # Adjust the height to account for padding.
+ height += (@sources.length - 1) * @padding
+ end
- montage = list.montage do
- self.gravity = Magick::NorthWestGravity
- # Transparent background.
- self.background_color = '#FFF0'
- # Allow each image to take up as much space as it needs.
- self.geometry = '+0+0'
- # columns=1, rows=Sources plus padding.
- self.tile = Magick::Geometry.new(1, sources_length * 2)
+ canvas = ChunkyPNG::Canvas.new(width, height)
+
+ # Add each source to the canvas.
+ @sources.each do |source|
+ canvas.compose(source.image, 0, position_of(source))
end
- # Remove the blank space from the bottom of the image.
- montage.crop!(0, 0, 0, (montage.first.rows) - @padding)
- montage.write("PNG32:#{@save_path}")
+ canvas.save(@save_path, :best_compression)
true
end
end # Sprite