forked from sysoftheworld/spritesheet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
decode.go
55 lines (49 loc) · 1.35 KB
/
decode.go
1
2
3
4
5
6
7
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
package spritesheet
import (
"image"
"image/draw"
)
// DecodeOpts provides the decoder with the necessary opts to split the spritesheet into seperate images
type DecodeOpts struct {
New func(r image.Rectangle) draw.Image // what format you want the new image to be, defaults to RGBA
Width, Height int
}
// Decode takes in a image, assumed to be a spritesheet, and based on the options passed will
// chop up the spritesheet into seperate images.
// a width and height are needed to know the bounds of each image
func Decode(in image.Image, opts *DecodeOpts) ([]image.Image, error) {
if in == nil {
return nil, nil
}
if opts == nil || opts.Width == 0 || opts.Height == 0 {
return nil, ErrBadDimensions
}
if opts.New == nil {
opts.New = NewRGBA
}
var (
row, column int
width, height = opts.Width, opts.Height
out []image.Image
bounds = in.Bounds()
)
for {
var (
min = image.Point{X: (bounds.Min.X + column) * width, Y: (bounds.Min.Y + row) * height}
max = image.Point{X: min.X + width, Y: min.Y + height}
subImg = image.Rectangle{Min: min, Max: max}
newImg = opts.New(subImg)
)
column++
if max.X >= bounds.Max.X {
row++
column = 0
}
if max.Y > bounds.Max.Y {
break
}
draw.Draw(newImg, subImg, in, newImg.Bounds().Min, draw.Over)
out = append(out, newImg)
}
return out, nil
}