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 from typing import Union, Tuple, Optional
21 from PIL import ImageFont
22 from displayio import Bitmap
24 from typing import Protocol
26 from typing_extensions import Protocol
28 __version__ = "0.0.0-auto.0"
29 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
32 class FontProtocol(Protocol):
33 """A protocol shared by `BuiltinFont` and classes in ``adafruit_bitmap_font``"""
35 def get_bounding_box(self) -> Union[Tuple[int, int], Tuple[int, int, int, int]]:
36 """Retrieve the maximum bounding box of any glyph in the font.
38 The four element version is ``(width, height, x_offset, y_offset)``.
39 The two element version is ``(width, height)``, in which
40 ``x_offset`` and ``y_offset`` are assumed to be zero.
43 def get_glyph(self, codepoint: int) -> Optional["Glyph"]:
44 """Retrieve the Glyph for a given code point
46 If the code point is not present in the font, `None` is returned.
50 """Simulate a font built into CircuitPython"""
53 self._font = ImageFont.load_default()
54 self._generate_bitmap(0x20, 0x7E)
56 def _generate_bitmap(self, start_range, end_range):
57 char_width, char_height = self.get_bounding_box()
58 self._bitmap = Bitmap(
59 char_width * (end_range - start_range + 1), char_height, 2
61 for character in range(start_range, end_range + 1):
62 ascii_char = chr(character)
63 ascii_mask = self._font.getmask(ascii_char, mode="1")
64 for y in range(char_height):
65 for x in range(char_width):
66 color = ascii_mask.getpixel((x, y))
67 character_position = character - start_range
68 self._bitmap[character_position * char_width + x, y] = (
72 def get_bounding_box(self):
73 """Returns the maximum bounds of all glyphs in the font in
74 a tuple of two values: width, height.
76 return self._font.getsize("M")
78 def get_glyph(self, codepoint):
79 """Returns a `fontio.Glyph` for the given codepoint or None if no glyph is available."""
80 if 0x20 <= codepoint <= 0x7E:
81 glyph_index = codepoint - 0x20
85 bounding_box = self._font.getsize(chr(codepoint))
86 width, height = bounding_box
89 tile_index=glyph_index,
100 """Bitmap containing all font glyphs starting with ASCII and followed by unicode. Use
101 `get_glyph` in most cases. This is useful for use with `displayio.TileGrid` and
102 `terminalio.Terminal`.
107 # pylint: disable=too-few-public-methods, invalid-name, too-many-arguments
109 """Storage of glyph info"""
111 def __init__(self, bitmap, tile_index, width, height, dx, dy, shift_x, shift_y):
117 self.shift_x = shift_x
118 self.shift_y = shift_y
119 self.tile_index = tile_index
122 # pylint: enable=too-few-public-methods, invalid-name, too-many-arguments