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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use crate::matrix::Matrix;
use crate::qr::Qr;
use crate::*;
pub struct SvgRenderer {
light: rendercommons::Color,
dark: rendercommons::Color,
w: usize,
h: usize,
qz: bool,
}
impl SvgRenderer {
pub fn new() -> Self {
Self {
light: rendercommons::Color::new(255, 255, 255),
dark: rendercommons::Color::new(0, 0, 0),
w: 200,
h: 200,
qz: true,
}
}
pub fn light_module(mut self, v: Color) -> Self {
self.light = v;
self
}
pub fn dark_module(mut self, v: Color) -> Self {
self.dark = v;
self
}
pub fn quiet_zone(mut self, v: bool) -> Self {
self.qz = v;
self
}
pub fn dimensions(mut self, w: usize, h: usize) -> Self {
self.w = w;
self.h = h;
self
}
pub fn render(&self, qr: &Qr) -> String {
self.render_matrix(&qr.matrix)
}
pub fn render_matrix(&self, matrix: &Matrix) -> String {
let cell_count = if self.qz {
matrix.size + 8
} else {
matrix.size
};
let cell_w = ((self.w as f64) / (cell_count as f64)).ceil() as usize;
let cell_h = ((self.h as f64) / (cell_count as f64)).ceil() as usize;
let w = cell_w * cell_count;
let h = cell_h * cell_count;
let mut res = String::from(format!(
"<?xml version=\"1.0\" standalone=\"yes\"?>
<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"
viewBox=\"0 0 {w} {h}\" shape-rendering=\"crispEdges\">
<rect x=\"0\" y=\"0\" width=\"{w}\" height=\"{h}\" fill=\"{light}\"/>
<path fill=\"{dark}\" d=\"",
w = w,
h = h,
light = self.light.to_hex_str(),
dark = self.dark.to_hex_str()
));
for y in 0..matrix.size {
let yp = if self.qz {
(y + 4) * cell_h
} else {
y * cell_h
};
for x in 0..matrix.size {
let xp = if self.qz {
(x + 4) * cell_w
} else {
x * cell_w
};
if matrix.is_dark(x, y) {
res.push_str(
format!(
"M{x} {y}h{w}v{h}H{x}V{y}",
x = xp,
y = yp,
w = cell_w,
h = cell_h
)
.as_str(),
);
}
}
}
res.push_str("\"/></svg>\n");
res
}
}