Module: RubySprites::Packer::HorizontalSmart

Defined in:
lib/lash-sprites/packer/horizontal_smart.rb

Class Method Summary collapse

Class Method Details

.pack(images, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/lash-sprites/packer/horizontal_smart.rb', line 8

def self.pack(images, options = {})
  width = 0
  height = 0
  
  images.sort! do |a, b|
    if a.height == b.height
      b.width <=> a.width
    else
      b.height <=> a.height
    end
  end

  blocks = []

  images.each do |img|
    next unless img.exists?
    smallest = nil
    exact = nil
    blocks.each do |block|
      next unless block.fits?(img)
      
      exact = block if (img.width == block.width || img.height == block.height) && (exact.nil? || block.area < exact.area)
      smallest = block if smallest.nil? || block.area < smallest.area
      
      break if smallest.area == img.area
    end

    if smallest
      if exact
        blocks.concat(split_block(blocks.delete(exact), img))
      else
        blocks.concat(split_block(blocks.delete(smallest), img))
      end
    else
      if width == 0 && height == 0
        b = Block.new(0, 0, img.width, img.height)
        width = img.width
        height = img.height
      else
        b = Block.new(width, 0, img.width, height)
        width += img.width
      end
      blocks.concat(split_block(b, img))
    end
  end

  return {:width => width, :height => height}
end

.split_block(block, img) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/lash-sprites/packer/horizontal_smart.rb', line 57

def self.split_block(block, img)
  blocks = []
  img.x = block.x
  img.y = block.y
  if (block.width - img.width) * img.height > (block.height - img.height) * img.width
    blocks.push Block.new(block.x + img.width, block.y, block.width - img.width, block.height) if block.width != img.width
    blocks.push Block.new(block.x, block.y + img.height, img.width, block.height - img.height) if block.height != img.height
  else
    blocks.push Block.new(block.x + img.width, block.y, block.width - img.width, img.height) if block.width != img.width
    blocks.push Block.new(block.x, block.y + img.height, block.width, block.height - img.height) if block.height != img.height
  end
  return blocks
end