| 1 |
use plotters::coord::Shift; |
| 2 |
use plotters::prelude::*; |
| 3 |
|
| 4 |
pub fn sierpinski_carpet( |
| 5 |
depth: u32, |
| 6 |
drawing_area: &DrawingArea<BitMapBackend, Shift>, |
| 7 |
) -> Result<(), Box<dyn std::error::Error>> { |
| 8 |
if depth > 0 { |
| 9 |
let sub_areas = drawing_area.split_evenly((3, 3)); |
| 10 |
for (idx, sub_area) in (0..).zip(sub_areas.iter()) { |
| 11 |
if idx != 4 { |
| 12 |
sub_area.fill(&BLUE)?; |
| 13 |
sierpinski_carpet(depth - 1, sub_area)?; |
| 14 |
} else { |
| 15 |
sub_area.fill(&WHITE)?; |
| 16 |
} |
| 17 |
} |
| 18 |
} |
| 19 |
Ok(()) |
| 20 |
} |
| 21 |
|
| 22 |
const OUT_FILE_NAME: &str = "plotters-doc-data/sierpinski.png"; |
| 23 |
fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 24 |
let root = BitMapBackend::new(OUT_FILE_NAME, (1024, 768)).into_drawing_area(); |
| 25 |
|
| 26 |
root.fill(&WHITE)?; |
| 27 |
|
| 28 |
let root = root |
| 29 |
.titled("Sierpinski Carpet Demo", ("sans-serif", 60))? |
| 30 |
.shrink(((1024 - 700) / 2, 0), (700, 700)); |
| 31 |
|
| 32 |
sierpinski_carpet(5, &root)?; |
| 33 |
|
| 34 |
// To avoid the IO failure being ignored silently, we manually call the present function |
| 35 |
root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir"); |
| 36 |
println!("Result has been saved to {}", OUT_FILE_NAME); |
| 37 |
|
| 38 |
Ok(()) |
| 39 |
} |
| 40 |
#[test] |
| 41 |
fn entry_point() { |
| 42 |
main().unwrap() |
| 43 |
} |