If all we wanted to do was display an entire bitmap image onto our display, we could probably stop here. We could just do something like display.show(bitmap) and our bitmap would show up. However, the CircuitPython displayio library adds a few extra layers to the mix. This is done for good reason (spoiler alert = games), but it may initially seem overly complex and confusing. Hopefully we can help clear that up here.

Let's start with the first item, the TileGrid class.


The TileGrid class slices up a source bitmap into multiple rectangular regions called tiles. You can have one or more tiles arranged in a 2D array called a grid. Thus the name TileGrid.

You specify the source bitmap with bitmap and you also need an associated pixel_shader to generate the pixel colors.

Then, you specify how many tiles the TileGrid will have using width and height. These are the number of tiles, not the number of pixels. The size of each tile will be the same and is specified by tile_width and tile_height. These are in units of pixels. Furthermore, the number must evenly divide into the source bitmap's dimensions. So you can't just specify anything. You can specify the initial contents of the tiles using default_tile. This is an index into the source bitmap's tiles and it can be changed later for each individual tile.

Finally, as we will see later, a TileGrid will be added to a Group. You specify the 2D location of the TileGrid relative to the Group with x and y.

Changing a Tile

In the example above, each tile has the default index of 0. This index refers to the tile index in the Source Bitmap. You can reassign any tile in the TileGrid to any of the available indices from the Source Bitmap. To do so, use the syntax:

tile_grid[tile_grid_index] = source_index

The tile_grid_index can either be the integer number for the tile index or an (x, y) tuple - both notations are shown in the TileGrid example above. The source_index is the integer number from the Source Bitmap - also shown in the example above.

Using our example from above, if we did something like this:

tile_grid[0] = 9
tile_grid[1] = 5
tile_grid[2] = 3
tile_grid[3] = 0

or this, which uses the other notation:

tile_grid[0, 0] = 9
tile_grid[1, 0] = 5
tile_grid[0, 1] = 3
tile_grid[1, 1] = 0

We would end up with something like this:

Note that nothing is changing in the Source Bitmap. Only the TileGrid is changed. You can do this over and over as many times as you want.

Also note that only the TileGrid will eventually be shown on the display. The Source Bitmap just lives in memory and serves up the graphical data used by the TileGrid.

This guide was first published on Apr 30, 2019. It was last updated on Feb 27, 2021.

This page (TileGrid) was last updated on Apr 15, 2019.

Text editor powered by tinymce.