1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use image::{GenericImage, ImageBuffer, Pixel};
use crate::definitions::{Clamp, Image};
use conv::ValueInto;
use std::f32;
use std::i32;
use crate::pixelops::weighted_sum;
use rusttype::{Font, Scale, point, PositionedGlyph};
pub fn draw_text_mut<'a, I>(
image: &'a mut I,
color: I::Pixel,
x: u32,
y: u32,
scale: Scale,
font: &'a Font<'a>,
text: &'a str,
) where
I: GenericImage,
<I::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
{
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let glyphs: Vec<PositionedGlyph<'_>> = font.layout(text, scale, offset).collect();
for g in glyphs {
if let Some(bb) = g.pixel_bounding_box() {
g.draw(|gx, gy, gv| {
let gx = gx as i32 + bb.min.x;
let gy = gy as i32 + bb.min.y;
let image_x = gx + x as i32;
let image_y = gy + y as i32;
let image_width = image.width() as i32;
let image_height = image.height() as i32;
if image_x >= 0 && image_x < image_width && image_y >= 0 && image_y < image_height {
let pixel = image.get_pixel(image_x as u32, image_y as u32);
let weighted_color = weighted_sum(pixel, color, 1.0 - gv, gv);
image.put_pixel(image_x as u32, image_y as u32, weighted_color);
}
})
}
}
}
pub fn draw_text<'a, I>(
image: &'a mut I,
color: I::Pixel,
x: u32,
y: u32,
scale: Scale,
font: &'a Font<'a>,
text: &'a str,
) -> Image<I::Pixel>
where
I: GenericImage,
<I::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
I::Pixel: 'static,
{
let mut out = ImageBuffer::new(image.width(), image.height());
out.copy_from(image, 0, 0);
draw_text_mut(&mut out, color, x, y, scale, font, text);
out
}