draw: Add ability to set individual char color

This commit is contained in:
Kenny Levinsen
2019-08-03 10:39:33 +02:00
parent c135f37b45
commit 9116399ddd
+56 -1
View File
@@ -58,13 +58,68 @@ pub fn draw_text(
Ok((x_max, y_max)) Ok((x_max, y_max))
} }
pub fn draw_text_individual_colors(
font_data: &'static [u8],
buf: &mut Buffer,
background_color: &Color,
color: &[Color],
size: f32,
s: &str,
) -> Result<(u32, u32), ::std::io::Error> {
// Load the font
// This only succeeds if collection consists of one font
let font = Font::from_bytes(font_data as &[u8]).expect("Error constructing Font");
// The font size to use
let scale = Scale::uniform(size);
let v_metrics = font.v_metrics(scale);
// layout the glyphs in a line with 20 pixels padding
let glyphs: Vec<_> = font
.layout(s, scale, point(0.0, v_metrics.ascent))
.collect();
let mut x_max: u32 = 0;
let mut y_max: u32 = 0;
let mut x_pos: usize = 0;
// Loop through the glyphs in the text, positing each one on a line
for glyph in glyphs {
if let Some(bounding_box) = glyph.pixel_bounding_box() {
if bounding_box.max.x > x_max as i32 {
x_max = bounding_box.max.x as u32;
}
if bounding_box.max.y > y_max as i32 {
y_max = bounding_box.max.y as u32;
}
// Draw the glyph into the image per-pixel by using the draw closure
glyph.draw(|x, y, o| {
let x = x + bounding_box.min.x as u32;
let y = y + bounding_box.min.y as u32;
let o = if o > 1.0 {
1.0
} else if o < 0.0 {
0.0
} else {
o
};
let _ = buf.put((x, y), &background_color.blend(&color[x_pos], o));
});
x_pos += 1;
}
}
Ok((x_max, y_max))
}
pub fn draw_text_fixed_width( pub fn draw_text_fixed_width(
font_data: &'static [u8], font_data: &'static [u8],
buf: &mut Buffer, buf: &mut Buffer,
background_color: &Color, background_color: &Color,
color: &Color, color: &Color,
size: f32, size: f32,
distances: Vec<u32>, distances: &[u32],
s: &str, s: &str,
) -> Result<(), ::std::io::Error> { ) -> Result<(), ::std::io::Error> {
// Load the font // Load the font