Make all measurements in inches by default
Getty Ritter
7 years ago
| 1 | 1 | use std::fmt::Display; |
| 2 | use std::fmt::{Formatter, Error}; | |
| 2 | 3 | use std::io::Write; |
| 3 | 4 | |
| 4 | 5 | /// An SVG document |
| 7 | 8 | size: (f64, f64), |
| 8 | 9 | } |
| 9 | 10 | |
| 11 | #[derive(Copy, Clone)] | |
| 12 | pub struct Inches { amt: f64 } | |
| 13 | ||
| 14 | impl Display for Inches { | |
| 15 | fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { | |
| 16 | self.amt.fmt(f)?; | |
| 17 | write!(f, "in") | |
| 18 | } | |
| 19 | } | |
| 20 | ||
| 21 | fn inches(amt: f64) -> Inches { Inches { amt } } | |
| 22 | ||
| 10 | 23 | fn xml_tag(w: &mut Vec<u8>, name: &str, attrs: &[(&str, &dyn Display)]) { |
| 11 | 24 | write!(w, "<{}", name); |
| 12 | 25 | for (k, v) in attrs { |
| 24 | 37 | } |
| 25 | 38 | |
| 26 | 39 | fn xml_close(w: &mut Vec<u8>, name: &str) { |
| 27 |
write!(w, "< |
|
| 40 | write!(w, "</{}>", name); | |
| 28 | 41 | } |
| 29 | 42 | |
| 30 | 43 | /// Create a new empty SVG document of the specified width and height |
| 52 | 65 | pub fn to_bytes(self) -> Vec<u8> { |
| 53 | 66 | let mut buf = Vec::new(); |
| 54 | 67 | let (w, h) = self.size; |
| 55 |
writeln!(buf, "<?xml version=\"1.0\" encoding=\"UTF-8\" |
|
| 68 | writeln!(buf, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); | |
| 56 | 69 | xml_open( |
| 57 | 70 | &mut buf, "svg", |
| 58 | 71 | &[("xmlns", &"http://www.w3.org/2000/svg"), |
| 59 | 72 | ("version", &"1.1"), |
| 60 | ("width", &w), | |
| 61 | ("height", &h), | |
| 73 | ("width", &inches(w)), | |
| 74 | ("height", &inches(h)), | |
| 75 | ("viewBox", &format!("0 0 {} {}", w, h)), | |
| 76 | ("stroke-width", &"0.0001in"), | |
| 62 | 77 | ], |
| 63 | 78 | ); |
| 64 | 79 | for elem in self.stuff { |
| 105 | 120 | buf, "circle", |
| 106 | 121 | &[("cx", &x), |
| 107 | 122 | ("cy", &y), |
| 108 |
("r", &"0. |
|
| 123 | ("r", &"0.01in"), | |
| 109 | 124 | ("fill", &"black"), |
| 110 | 125 | ], |
| 111 | 126 | ); |
| 150 | 165 | } |
| 151 | 166 | |
| 152 | 167 | /// Draw a line segment from this point to another point |
| 153 |
pub fn |
|
| 168 | pub fn to(mut self, x: f64, y: f64) -> Line { | |
| 154 | 169 | self.points.push((x, y)); |
| 155 | 170 | self |
| 156 | 171 | } |