diff --git a/src/font.rs b/src/font.rs index 9d86d5e..d16814a 100644 --- a/src/font.rs +++ b/src/font.rs @@ -44,12 +44,17 @@ impl<'a> FontRenderer<'a> { text: T, pos: Position, ) { + if pos.x > 240 || pos.y > 240 { + // Everything would be out-of-bounds + return; + } + let glyphs = self .font .layout(&text.into(), self.scale, self.offset) .collect::>(); - let width = libm::ceil( + let text_width = libm::ceil( glyphs .iter() .rev() @@ -58,14 +63,17 @@ impl<'a> FontRenderer<'a> { .unwrap_or(0.0) as f64, ) as usize; - let mut pixel_data = vec![Rgb565::white(); self.height as usize * width]; + let width = (text_width + pos.x as usize).min(240) - pos.x as usize; + let height = (self.height + pos.y as u32).min(240) - pos.y as u32; + + let mut pixel_data = vec![Rgb565::white(); height as usize * width]; for g in glyphs { if let Some(bb) = g.pixel_bounding_box() { g.draw(|x, y, cov| { let x = bb.min.x + x as i32; let y = bb.min.y + y as i32; - if x >= 0 && y >= 0 && x < width as i32 && y < self.height as i32 { + if x >= 0 && y >= 0 && x < width as i32 && y < height as i32 { let col = 255 - (255. * cov) as u8; pixel_data[(x + y * width as i32) as usize] = Rgb565(col, col, col); } @@ -77,7 +85,7 @@ impl<'a> FontRenderer<'a> { pos, Position { x: pos.x + width as u16 - 1, - y: pos.y + self.height as u16 - 1, + y: pos.y + height as u16 - 1, }, ); display.write(display::Writeable::Data( diff --git a/src/main.rs b/src/main.rs index 7e4deaa..078f40c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -112,7 +112,7 @@ fn main() -> ! { let font_renderer = FontRenderer::create(30); - font_renderer.render(&mut display, "Hello World!", Position::new(0, 0)); + font_renderer.render(&mut display, "Hello World!", Position::new(70, 220)); loop { let delay_start = Instant::now();