]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - fontio.py
Basic fontio wrapper added
[hackapet/Adafruit_Blinka_Displayio.git] / fontio.py
1 """
2 `fontio`
3 """
4
5 __version__ = "0.0.0-auto.0"
6 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
7
8 from displayio import Bitmap
9 from PIL import ImageFont
10
11
12 class BuiltinFont:
13     def __init__(self):
14         self._font = ImageFont.load_default()
15         ascii = ""
16         for character in range(0x20, 0x7F):
17             ascii += chr(character)
18         self._font.getmask(ascii)
19         bmp_size = self._font.getsize(ascii)
20         self._bitmap = Bitmap(bmp_size[0], bmp_size[1], 2)
21         ascii_mask = self._font.getmask(ascii, mode="1")
22         for x in range(bmp_size[0]):
23             for y in range(bmp_size[1]):
24                 self._bitmap[x, y] = 1 if ascii_mask.getpixel((x, y)) else 0
25
26     def _get_glyph_index(self, charcode):
27         if 0x20 <= charcode <= 0x7E:
28             return charcode - 0x20
29
30     def get_bounding_box(self):
31         """Returns the maximum bounds of all glyphs in the font in a tuple of two values: width, height."""
32         return self._font.getsize("M")
33
34     def get_glyph(self, codepoint):
35         """Returns a `fontio.Glyph` for the given codepoint or None if no glyph is available."""
36         bounding_box = self._font.getsize(chr(codepoint))
37         return Glyph(
38             bitmap=self._bitmap,
39             tile_index=self._get_glyph_index(codepoint),
40             width=bounding_box[0],
41             height=bounding_box[1],
42             dx=0,
43             dy=0,
44             shift_x=0,
45             shift_y=0,
46         )
47
48     @property
49     def bitmap(self):
50         """Bitmap containing all font glyphs starting with ASCII and followed by unicode. Use `get_glyph` in most cases. This is useful for use with `displayio.TileGrid` and `terminalio.Terminal`.
51         """
52         return self._bitmap
53
54
55 class Glyph:
56     def __init__(self, *, bitmap, tile_index, width, height, dx, dy, shift_x, shift_y):
57         self.bitmap = bitmap
58         self.width = width
59         self.height = height
60         self.dx = dx
61         self.dy = dy
62         self.shift_x = shift_x
63         self.shift_y = shift_y
64         self.tile_index = tile_index