Class: Kin::Sprites::ImageGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/kin/sprites/image_generator.rb

Overview

Responsible for taking source icon files and creating a sprite.

Constant Summary collapse

IconNotReadable =
Class.new(SpriteError)
TargetNotWriteable =
Class.new(SpriteError)

Instance Method Summary collapse

Constructor Details

#initialize(set, source_dir) ⇒ ImageGenerator

Creates a new Generator instance.

Parameters:

  • set (IconSet)

    An IconSet instance.

  • source_dir (String)

    A path to the directory in which the source files reside.



20
21
22
# File 'lib/kin/sprites/image_generator.rb', line 20

def initialize(set, source_dir)
  @set, @source_dir = set, source_dir
end

Instance Method Details

#save(path) ⇒ Object

Uses RMagick to create a transparent PNG containing the individual icons as a sprite.

If a file already exists at the given path it will be overwritten.

Parameters:

  • path (String)

    The path at which to save the sprite.

Raises:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kin/sprites/image_generator.rb', line 45

def save(path)
  list = @set.inject(Magick::ImageList.new) do |m, icon|
    m << Magick::Image.read(File.join(@source_dir, "#{icon}.png"))[0]
  end

  # RMagick uses instance_eval, @set isn't available in the block below.
  set_length = @set.length

  montage = list.montage do
    # Transparent background.
    self.background_color = '#FFF0'
    # Each icon is 16x16 with 12 pixels of top & bottom padding = 16x40.
    self.geometry = Magick::Geometry.new(16, 16, 0, 12)
    self.tile = Magick::Geometry.new(1, set_length)
  end

  # Remove the blank space from both the top and bottom of the image.
  montage.crop!(0, 12, 0, (40 * set_length) - 24)
  montage.write("PNG32:#{path}")
rescue Magick::ImageMagickError => ex
  # Nicely rescue and re-raise if the target directory wasn't writable,
  # or if one of the icon files could not be opened.
  case ex.message
    when /Permission denied/ then raise TargetNotWriteable, ex.message
    when /unable to open/    then raise IconNotReadable, ex.message
    else                          raise ex
  end
end