1 | use plotters::prelude::*; |
2 | |
3 | fn snowflake_iter(points: &[(f64, f64)]) -> Vec<(f64, f64)> { |
4 | let mut ret = vec![]; |
5 | for i in 0..points.len() { |
6 | let (start, end) = (points[i], points[(i + 1) % points.len()]); |
7 | let t = ((end.0 - start.0) / 3.0, (end.1 - start.1) / 3.0); |
8 | let s = ( |
9 | t.0 * 0.5 - t.1 * (0.75f64).sqrt(), |
10 | t.1 * 0.5 + (0.75f64).sqrt() * t.0, |
11 | ); |
12 | ret.push(start); |
13 | ret.push((start.0 + t.0, start.1 + t.1)); |
14 | ret.push((start.0 + t.0 + s.0, start.1 + t.1 + s.1)); |
15 | ret.push((start.0 + t.0 * 2.0, start.1 + t.1 * 2.0)); |
16 | } |
17 | ret |
18 | } |
19 | |
20 | const OUT_FILE_NAME: &'static str = "plotters-doc-data/snowflake.png" ; |
21 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
22 | let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); |
23 | |
24 | root.fill(&WHITE)?; |
25 | |
26 | let mut chart = ChartBuilder::on(&root) |
27 | .caption("Koch's Snowflake" , ("sans-serif" , 50)) |
28 | .build_cartesian_2d(-2.0..2.0, -1.5..1.5)?; |
29 | |
30 | let mut snowflake_vertices = { |
31 | let mut current: Vec<(f64, f64)> = vec![ |
32 | (0.0, 1.0), |
33 | ((3.0f64).sqrt() / 2.0, -0.5), |
34 | (-(3.0f64).sqrt() / 2.0, -0.5), |
35 | ]; |
36 | for _ in 0..6 { |
37 | current = snowflake_iter(¤t[..]); |
38 | } |
39 | current |
40 | }; |
41 | |
42 | chart.draw_series(std::iter::once(Polygon::new( |
43 | snowflake_vertices.clone(), |
44 | &RED.mix(0.2), |
45 | )))?; |
46 | snowflake_vertices.push(snowflake_vertices[0]); |
47 | chart.draw_series(std::iter::once(PathElement::new(snowflake_vertices, &RED)))?; |
48 | |
49 | // To avoid the IO failure being ignored silently, we manually call the present function |
50 | root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir" ); |
51 | println!("Result has been saved to {}" , OUT_FILE_NAME); |
52 | Ok(()) |
53 | } |
54 | #[test] |
55 | fn entry_point() { |
56 | main().unwrap() |
57 | } |
58 | |