Class: CSSSprites::ImageGrid

Inherits:
Object
  • Object
show all
Defined in:
lib/css_sprites/image_grid.rb

Instance Method Summary collapse

Constructor Details

#initialize(images, options = {}) ⇒ ImageGrid

Returns a new instance of ImageGrid.



2
3
4
5
6
7
8
# File 'lib/css_sprites/image_grid.rb', line 2

def initialize(images, options = {})
  @images = images
  @name = options.fetch(:name, 'untitled')
  @stacking = options.fetch(:stacking, :horizontal)

  arrange_images!
end

Instance Method Details

#each_with_index(&block) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/css_sprites/image_grid.rb', line 57

def each_with_index(&block)
  @grid.each.with_index do |row, n|
    row.each.with_index do |image, k|
      block.call(image[:image], n, k)
    end
  end
end

#image_name(row, column) ⇒ Object



23
24
25
# File 'lib/css_sprites/image_grid.rb', line 23

def image_name(row, column)
  File.basename(@grid[row][column][:filename], '.*')
end

#image_x_offset(row, column) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/css_sprites/image_grid.rb', line 27

def image_x_offset(row, column)
  return 0 if column == 0 || @images.empty?

  @grid[row][0..(column - 1)].inject(0) do |sum, image|
    sum += image[:image].columns
  end
end

#image_y_offset(row, column = 0) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/css_sprites/image_grid.rb', line 35

def image_y_offset(row, column = 0)
  return 0 if row == 0 || @images.empty?

  row_heights = @grid[0..(row - 1)].map do |row|
    row.map { |image| image[:image].rows }.max
  end

  row_heights.inject(0, :+)
end

#nameObject



19
20
21
# File 'lib/css_sprites/image_grid.rb', line 19

def name
  @name
end

#to_imageObject



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/css_sprites/image_grid.rb', line 45

def to_image
  return nil if @images.empty?

  image_grid = Magick::Image.new(total_width, total_height) { self.background_color = 'transparent' }

  each_with_index do |image, n, k|
    image_grid = image_grid.composite(image, image_x_offset(n, k), image_y_offset(n), Magick::OverCompositeOp)
  end

  image_grid
end

#total_columnsObject



84
85
86
# File 'lib/css_sprites/image_grid.rb', line 84

def total_columns
  @grid.map { |row| row.size }.max
end

#total_heightObject



15
16
17
# File 'lib/css_sprites/image_grid.rb', line 15

def total_height
  image_y_offset(total_rows)
end

#total_rowsObject



80
81
82
# File 'lib/css_sprites/image_grid.rb', line 80

def total_rows
  @grid.size
end

#total_widthObject



10
11
12
13
# File 'lib/css_sprites/image_grid.rb', line 10

def total_width
  row_widths = @grid.map.with_index { |row, index| image_x_offset(index, row.size) }
  row_widths.max
end