Module: Spritopia

Extended by:
Spritopia
Includes:
ChunkyPNG
Included in:
Spritopia
Defined in:
lib/spritopia.rb,
lib/spritopia/version.rb

Defined Under Namespace

Modules: CLI

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#process_file(file) ⇒ Object



35
36
37
38
39
40
41
42
43
44
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/spritopia.rb', line 35

def process_file(file)
  raise "File should be a .sprite file" unless file =~ /\.sprite$/
  basename = File.basename(file, ".sprite")
  dir  = File.dirname(file)
  basefilename = File.join(dir, basename)

  File.file?(file) or raise "The file #{file} did not exists"

  # Get the list of the images

  files = File.read(file).split("\n").map{|f| f.strip}

  # Calculate height and width
  sizes = files.map do |f|
    image = Image.from_file(File.join(dir,f))
    [image.width, image.height]
  end

  height = sizes.inject( 0 ) { |memo,i| memo+i[1] }
  width = sizes.inject( 0 ) { |memo,i| memo > i[0] ? memo : i[0] }


  # Generate the sprite
  canvas = Image.new(width,height)

  file_info = {}

  files.inject(0) { |current_height, filename|
    new_image = Image.from_file(File.join(dir,filename))
    canvas.replace!(new_image, 0, current_height)

    file_info[filename] = {:width => new_image.width, :height => new_image.height, :x => 0, :y => current_height, :x2 => new_image.width, :y2 => new_image.height + current_height }


    current_height + new_image.height
  }

  # Save the sprite

  puts File.basename(file,".sprite")

  canvas.save(basefilename+".png")

  # Save the json

  File.open(basefilename + ".json", "w") do |f|
    f.write file_info.to_json
  end

  true

end