Clip text correctly when out-of-bounds

This commit is contained in:
Sofia 2026-05-13 21:46:11 +03:00
parent 8d9f1ffbe9
commit f4adebeaef
2 changed files with 13 additions and 5 deletions

View File

@ -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::<Vec<_>>();
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(

View File

@ -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();