stevenkhan commited on
Commit
8df383d
·
verified ·
1 Parent(s): 97399bd

Upload spectral-font/src/metrics.rs

Browse files
Files changed (1) hide show
  1. spectral-font/src/metrics.rs +62 -0
spectral-font/src/metrics.rs ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use fontdue::{Font, LineMetrics};
2
+
3
+ #[derive(Clone, Copy, Debug, PartialEq)]
4
+ pub struct FontMetrics {
5
+ pub cell_width: f32,
6
+ pub cell_height: f32,
7
+ pub baseline: f32,
8
+ pub underline_position: f32,
9
+ pub underline_thickness: f32,
10
+ pub strikethrough_position: f32,
11
+ pub strikethrough_thickness: f32,
12
+ pub ascent: f32,
13
+ pub descent: f32,
14
+ pub line_gap: f32,
15
+ }
16
+
17
+ impl FontMetrics {
18
+ pub fn from_fontdue(
19
+ font: &Font,
20
+ px: f32,
21
+ adjust_height: Option<f32>,
22
+ adjust_width: Option<f32>,
23
+ ) -> Self {
24
+ let h = font.horizontal_line_metrics(px).unwrap_or(LineMetrics {
25
+ ascent: px * 0.8,
26
+ descent: px * 0.2,
27
+ line_gap: 0.0,
28
+ new_line_size: px,
29
+ });
30
+
31
+ let v = font.vertical_line_metrics(px).unwrap_or(LineMetrics {
32
+ ascent: px, descent: 0.0, line_gap: 0.0, new_line_size: px,
33
+ });
34
+
35
+ let mut cell_width = v.new_line_size;
36
+ let mut cell_height = h.new_line_size;
37
+
38
+ let mut max_advance = 0.0f32;
39
+ for ch in (32u8..=126).map(|b| b as char) {
40
+ let idx = font.lookup_glyph_index(ch);
41
+ let (m, _) = font.rasterize_indexed(idx, px);
42
+ max_advance = max_advance.max(m.advance_width);
43
+ }
44
+ if max_advance > 0.0 { cell_width = max_advance; }
45
+
46
+ if let Some(adj) = adjust_height { cell_height *= adj; }
47
+ if let Some(adj) = adjust_width { cell_width *= adj; }
48
+
49
+ Self {
50
+ cell_width,
51
+ cell_height,
52
+ baseline: h.ascent,
53
+ underline_position: h.ascent * 0.9,
54
+ underline_thickness: px * 0.05,
55
+ strikethrough_position: h.ascent * 0.55,
56
+ strikethrough_thickness: px * 0.05,
57
+ ascent: h.ascent,
58
+ descent: h.descent,
59
+ line_gap: h.line_gap,
60
+ }
61
+ }
62
+ }