1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
7 ================================================================================
11 **Software and Dependencies:**
14 https://github.com/adafruit/Adafruit_Blinka/releases
16 * Author(s): Melissa LeBlanc-Williams
20 __version__ = "0.0.0-auto.0"
21 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
25 """Map a pixel palette_index to a full color. Colors are transformed to the display’s
26 format internally to save memory.
29 def __init__(self, color_count):
30 """Create a Palette object to store a set number of colors."""
31 self._needs_refresh = False
34 for _ in range(color_count):
35 self._colors.append(self._make_color(0))
36 self._update_rgba(len(self._colors) - 1)
38 def _update_rgba(self, index):
39 color = self._colors[index]["rgb888"]
40 transparent = self._colors[index]["transparent"]
41 self._colors[index]["rgba"] = (
45 0 if transparent else 0xFF,
48 def _make_color(self, value, transparent=False):
50 "transparent": transparent,
52 "rgba": (0, 0, 0, 255),
54 if isinstance(value, (tuple, list, bytes, bytearray)):
55 value = (value[0] & 0xFF) << 16 | (value[1] & 0xFF) << 8 | value[2] & 0xFF
56 elif isinstance(value, int):
57 if not 0 <= value <= 0xFFFFFF:
58 raise ValueError("Color must be between 0x000000 and 0xFFFFFF")
60 raise TypeError("Color buffer must be a buffer, tuple, list, or int")
61 color["rgb888"] = value
62 self._needs_refresh = True
67 """Returns the number of colors in a Palette"""
68 return len(self._colors)
70 def __setitem__(self, index, value):
71 """Sets the pixel color at the given index. The index should be
72 an integer in the range 0 to color_count-1.
74 The value argument represents a color, and can be from 0x000000 to 0xFFFFFF
75 (to represent an RGB value). Value can be an int, bytes (3 bytes (RGB) or
76 4 bytes (RGB + pad byte)), bytearray, or a tuple or list of 3 integers.
78 if self._colors[index]["rgb888"] != value:
79 self._colors[index] = self._make_color(value)
80 self._update_rgba(index)
82 def __getitem__(self, index):
83 if not 0 <= index < len(self._colors):
84 raise ValueError("Palette index out of range")
85 return self._colors[index]
87 def make_transparent(self, palette_index):
88 """Set the palette index to be a transparent color"""
89 self._colors[palette_index]["transparent"] = True
90 self._update_rgba(palette_index)
92 def make_opaque(self, palette_index):
93 """Set the palette index to be an opaque color"""
94 self._colors[palette_index]["transparent"] = False
95 self._update_rgba(palette_index)
97 def _get_palette(self):
98 """Generate a palette for use with PIL"""
100 for color in self._colors:
101 palette += color["rgba"][0:3]
104 def _get_alpha_palette(self):
105 """Generate an alpha channel palette with white being
106 opaque and black being transparent"""
108 for color in self._colors:
110 palette += [0 if color["transparent"] else 255]