image_builder/text.rs
1use image::Rgba;
2use rusttype::Scale;
3
4use crate::colors::{self, Color};
5
6/// Content and formatting of a text.
7#[derive(Clone)]
8pub struct Text {
9 content: String,
10 size: u32,
11 position: (u32, u32),
12 font_name: String,
13 color: Color,
14}
15impl Text {
16 /// This method instantiates a specifications of a text.
17 /// ## Example
18 /// ```
19 /// use image_builder::Text;
20 ///
21 /// Text::new("Any text here");
22 /// ```
23 pub fn new(content: &str) -> Text {
24 let content = String::from(content);
25
26 Text {
27 content,
28 size: 14,
29 position: (0, 0),
30 font_name: String::from("default"),
31 color: colors::BLACK,
32 }
33 }
34
35 /// Define the size of the text.
36 /// ## Example
37 /// ```
38 /// use image_builder::Text;
39 ///
40 /// Text::new("Any text here")
41 /// .size(50);
42 /// ```
43 pub fn size(&mut self, size: u32) -> Self {
44 self.size = size;
45 self.clone()
46 }
47
48 /// This method allows you to adjust the position of the text within the image being constructed.
49 /// ## Example
50 /// ```
51 /// use image_builder::Text;
52 ///
53 /// Text::new("Any text here")
54 /// .position(100, 100);
55 /// ```
56 pub fn position(&mut self, x: u32, y: u32) -> Self {
57 self.position = (x, y);
58 self.clone()
59 }
60
61 /// This method is used to set the font of a text, but it's important to remember to import the
62 /// font using the add_custom_font method of the [`crate::Image`] structure (refer to the documentation
63 /// for more details). Trying to use a font that hasn't been imported will result in an error
64 /// in the application. Make sure to import the font correctly to avoid panics.
65 /// ## Example
66 /// ```
67 /// use image_builder::Text;
68 ///
69 /// Text::new("Any text here")
70 /// .font("Any font");
71 /// ```
72 pub fn font(&mut self, font_name: &str) -> Self {
73 self.font_name = String::from(font_name);
74 self.clone()
75 }
76
77 /// Define the color of the text.
78 /// ## Examples
79 /// ```
80 /// use image_builder::{Text, colors};
81 ///
82 /// Text::new("Any text here")
83 /// .color(colors::BLUE);
84 /// ```
85 /// ```
86 /// use image_builder::Text;
87 ///
88 /// Text::new("Any text here")
89 /// .color([30, 90, 150, 255]); // rgba values
90 /// ```
91 pub fn color(&mut self, color: Color) -> Self {
92 self.color = color;
93 self.clone()
94 }
95}
96
97#[derive(Clone)]
98pub struct TextValues<'a> {
99 pub color: Rgba<u8>,
100 pub x: i32,
101 pub y: i32,
102 pub font_name: &'a str,
103 pub scale: Scale,
104 pub content: &'a str,
105}
106
107pub fn extract<'a>(text: &'a Text) -> TextValues<'a> {
108 let scale = Scale {
109 x: text.size as f32,
110 y: text.size as f32,
111 };
112 TextValues {
113 color: Rgba(text.color),
114 x: text.position.0 as i32,
115 y: text.position.1 as i32,
116 scale,
117 font_name: text.font_name.as_str(),
118 content: &text.content,
119 }
120}