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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
extern crate qrcode;
use self::qrcode::types::Color::Dark as QrDark;
use self::qrcode::QrCode;
pub use qrcode::types::QrError;
const QUIET_ZONE: usize = 4;
const LIGHT_COLOR_RGBA: (f64, f64, f64, f64) = (1.0, 1.0, 1.0, 1.0);
const DARK_COLOR_RGBA: (f64, f64, f64, f64) = (0.0, 0.0, 0.0, 1.0);
pub fn draw(cr: &cairo::Context, width: f64, height: f64, text: &str) -> Result<(), QrError> {
Qr2Cairo::new(width, height, text)?.draw(cr);
Ok(())
}
struct Qr2Cairo {
width: f64,
height: f64,
qr_code: QrCode,
}
impl Qr2Cairo {
pub fn new(width: f64, height: f64, text: &str) -> Result<Qr2Cairo, QrError> {
let qr_code = QrCode::new(text)?;
return Ok(Qr2Cairo {
width,
height,
qr_code,
});
}
pub fn draw(&self, cr: &cairo::Context) {
self.set_up_scaling(cr);
self.draw_background(cr);
self.draw_dark_boxes(cr);
}
fn draw_dark_boxes(&self, cr: &cairo::Context) {
let vec = self.qr_code.to_colors();
let (r, g, b, a) = DARK_COLOR_RGBA;
cr.set_source_rgba(r, g, b, a);
for row in 0..self.width_in_blocks_without_quiet() {
for col in 0..self.width_in_blocks_without_quiet() {
let vec_pos = row * self.width_in_blocks_without_quiet() + col;
if vec[vec_pos] == QrDark {
cr.rectangle(
(QUIET_ZONE + col) as f64,
(QUIET_ZONE + row) as f64,
1.0,
1.0,
);
}
}
}
cr.fill();
}
fn set_up_scaling(&self, cr: &cairo::Context) {
let drawingsize = f64::min(self.width, self.height);
let px_per_block = drawingsize / (self.width_in_blocks() as f64);
let move_x = f64::max(0.0, self.width - drawingsize) / 2.0;
let move_y = f64::max(0.0, self.height - drawingsize) / 2.0;
cr.translate(move_x, move_y);
cr.scale(px_per_block, px_per_block);
}
fn draw_background(&self, cr: &cairo::Context) {
let (r, g, b, a) = LIGHT_COLOR_RGBA;
cr.set_source_rgba(r, g, b, a);
cr.rectangle(
0.0,
0.0,
self.width_in_blocks() as f64,
self.width_in_blocks() as f64,
);
cr.fill();
}
fn width_in_blocks_without_quiet(&self) -> usize {
self.qr_code.width()
}
fn width_in_blocks(&self) -> usize {
self.width_in_blocks_without_quiet() + QUIET_ZONE * 2
}
}