cas_graph/
text_align.rs

1use cairo::{Context, Error, TextExtents};
2
3/// A trait to add the `show_text_align` to the [`Context`] type.
4pub trait ShowTextAlign {
5    /// Shows the given text at the given `(x, y)` position, with the given alignment.
6    ///
7    /// Draw text to the given context with the given alignment point.
8    ///
9    /// By default, text is rendered with the bottom left corner of the text at the given `(x, y)`
10    /// point. This function allows you to specify an alignment point, which is a pair of `(x, y)`
11    /// values, each between `0.0` and `1.0`, indicating the horizontal and vertical alignment of the
12    /// text, respectively.
13    ///
14    /// For example, `(0.0, 0.0)` will align the bottom left corner of the text to the given `(x, y)`
15    /// point, `(0.5, 0.5)` will center the text, `(1.0, 1.0)` will align the top right corner of the
16    /// text to the given `(x, y)` point, etc.
17    fn show_text_align(
18        &self,
19        text: &str,
20        point: (f64, f64),
21        align: (f64, f64),
22    ) -> Result<TextExtents, Error>;
23
24    /// Shows the given text at the given `(x, y)` position, with the given alignment, using the
25    /// provided [`TextExtents`] to calculate the alignment.
26    ///
27    /// This is useful if you have already calculated the [`TextExtents`] for the text you want to
28    /// draw, and want to avoid calculating them again.
29    fn show_text_align_with_extents(
30        &self,
31        text: &str,
32        point: (f64, f64),
33        align: (f64, f64),
34        extents: &TextExtents,
35    ) -> Result<(), Error>;
36}
37
38impl ShowTextAlign for Context {
39    fn show_text_align(
40        &self,
41        text: &str,
42        (x, y): (f64, f64),
43        align: (f64, f64),
44    ) -> Result<TextExtents, Error> {
45        let extents = self.text_extents(text)?;
46        self.show_text_align_with_extents(text, (x, y), align, &extents)?;
47        Ok(extents)
48    }
49
50    fn show_text_align_with_extents(
51        &self,
52        text: &str,
53        (x, y): (f64, f64),
54        align: (f64, f64),
55        extents: &TextExtents,
56    ) -> Result<(), Error> {
57        let x = x - extents.width() * align.0;
58        let y = y + extents.height() * align.1;
59        self.move_to(x, y);
60        self.show_text(text)
61    }
62}