microbit_text/image.rs
1//! Static 5×5 black-and-white images.
2
3use tiny_led_matrix::{Render, MAX_BRIGHTNESS};
4
5/// A 5×5 image supporting only two levels of brightness (on and off).
6///
7/// Uses 5 bytes of storage.
8///
9/// For display, each pixel is treated as having brightness either 0 or
10/// [MAX_BRIGHTNESS].
11///
12/// [MAX_BRIGHTNESS]: tiny_led_matrix::MAX_BRIGHTNESS
13
14#[derive(Copy, Clone, Debug)]
15pub struct BitImage (
16 [u8; 5]
17);
18
19impl BitImage {
20
21 /// Constructs a BitImage from an array of brightnesses.
22 ///
23 /// The data should be an array of 5 rows (top first), each of which is an
24 /// array of 5 values (left first). Each value should be either 0 or 1.
25 ///
26 /// # Example
27 ///
28 /// ```
29 /// const HEART: BitImage = BitImage::new(&[
30 /// [0, 1, 0, 1, 0],
31 /// [1, 0, 1, 0, 1],
32 /// [1, 0, 0, 0, 1],
33 /// [0, 1, 0, 1, 0],
34 /// [0, 0, 1, 0, 0],
35 /// ]);
36 /// ```
37 pub const fn new(im: &[[u8; 5]; 5]) -> BitImage {
38 const fn row_byte(row: [u8; 5]) -> u8 {
39 row[0] | row[1]<<1 | row[2]<<2 | row[3]<<3 | row[4]<<4
40 }
41 BitImage([
42 row_byte(im[0]),
43 row_byte(im[1]),
44 row_byte(im[2]),
45 row_byte(im[3]),
46 row_byte(im[4]),
47 ])
48 }
49
50 /// Returns a new blank BitImage.
51 ///
52 /// All pixel values are 0.
53 pub const fn blank() -> BitImage {
54 BitImage([0; 5])
55 }
56
57}
58
59impl Render for BitImage {
60 fn brightness_at(&self, x: usize, y: usize) -> u8 {
61 let rowdata = self.0[y];
62 if rowdata & (1<<x) != 0 {MAX_BRIGHTNESS as u8} else {0}
63 }
64}
65
66impl Render for &BitImage {
67 fn brightness_at(&self, x: usize, y: usize) -> u8 {
68 BitImage::brightness_at(self, x, y)
69 }
70}
71