Pyglet.image.ImageGrid() - indexing from top left

341 Views Asked by At

there.

Using pyglet.image.ImageGrid(), is there any way to start off the grid from the top left, instead of the bottom left?

3

There are 3 best solutions below

0
On BEST ANSWER

So, the only 'awfull' solution I currently have is:

  1. To verticaly flip the image on the drive
  2. Load the image as a texture and flip it back with get_texture()
  3. Put it into an ImageGrid()
  4. Reverse() the ImageGrid-sequence
0
On

This question is 4 years old, but since it's one of the top results on Google I thought I'd share my answer:

def reverse_rows(grid, columns):
    # split the grid into rows
    temp = [grid[i:i + int(columns)] for i in range(0, len(grid), int(columns))]
    temp.reverse()        # reverse the order of the rows
    reversed = []
    for grid in temp:     # reassemble the list
        reversed += grid
    return reversed       # and return the reversed list

Note that this returns a list of textures, not an ImageGrid or TextureGrid, so you might lose some functionality.

0
On

You can use this FlippedImageGrid class. Credits to caffeinepills

import pyglet


class TopLeftTextureGrid(pyglet.image.TextureGrid):

    def __init__(self, grid):
        image = grid.get_texture()
        if isinstance(image, TextureRegion):
            owner = image.owner
        else:
            owner = image

        super(TextureGrid, self).__init__(
            image.x, image.y, image.z, image.width, image.height, owner
        )

        items = []
        y = image.height - grid.item_height
        for row in range(grid.rows):
            x = 0
            for col in range(grid.columns):
                items.append(
                    self.get_region(x, y, grid.item_width, grid.item_height)
                )
                x += grid.item_width + grid.column_padding
            y -= grid.item_height + grid.row_padding

        self.items = items
        self.rows = grid.rows
        self.columns = grid.columns
        self.item_width = grid.item_width
        self.item_height = grid.item_height


class FlippedImageGrid(pyglet.image.ImageGrid):

    def _update_items(self):
        if not self._items:
            self._items = []
            y = self.image.height - self.item_height
            for row in range(self.rows):
                x = 0
                for col in range(self.columns):
                    self._items.append(
                        self.image.get_region(
                            x, y, self.item_width, self.item_height
                        )
                    )
                    x += self.item_width + self.column_padding
                y -= self.item_height + self.row_padding

    def get_texture_sequence(self):
        if not self._texture_grid:
            self._texture_grid = TopLeftTextureGrid(self)
        return self._texture_grid