/
image_array.py
49 lines (40 loc) · 1.26 KB
/
image_array.py
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
from pygame import Rect
from albow.resource import get_image
class ImageArray(object):
def __init__(self, image, shape):
self.image = image
self.shape = shape
if isinstance(shape, tuple):
self.nrows, self.ncols = shape
else:
self.nrows = 1
self.ncols = shape
iwidth, iheight = image.get_size()
self.size = iwidth // self.ncols, iheight // self.nrows
def __len__(self):
return self.shape
def __getitem__(self, index):
image = self.image
nrows = self.nrows
if nrows == 1:
row = 0
col = index
else:
row, col = index
# left = iwidth * col // ncols
#top = iheight * row // nrows
#width = iwidth // ncols
#height = iheight // nrows
width, height = self.size
left = width * col
top = height * row
return image.subsurface(left, top, width, height)
def get_rect(self):
return Rect((0, 0), self.size)
image_array_cache = {}
def get_image_array(name, shape, **kwds):
result = image_array_cache.get(name)
if not result:
result = ImageArray(get_image(name, **kwds), shape)
image_array_cache[name] = result
return result