| 1 | //! PIC rendering support. |
| 2 | //! |
| 3 | //! # Example |
| 4 | //! |
| 5 | //! ``` |
| 6 | //! use qrcode::QrCode; |
| 7 | //! use qrcode::render::pic; |
| 8 | //! |
| 9 | //! let code = QrCode::new(b"Hello").unwrap(); |
| 10 | //! let pic = code.render::<pic::Color>().build(); |
| 11 | //! println!("{}", pic); |
| 12 | |
| 13 | #![cfg(feature = "pic")] |
| 14 | |
| 15 | use std::fmt::Write; |
| 16 | |
| 17 | use crate::render::{Canvas as RenderCanvas, Pixel}; |
| 18 | use crate::types::Color as ModuleColor; |
| 19 | |
| 20 | /// A PIC color. |
| 21 | #[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 22 | pub struct Color; |
| 23 | |
| 24 | impl Pixel for Color { |
| 25 | type Canvas = Canvas; |
| 26 | type Image = String; |
| 27 | |
| 28 | fn default_color(_color: ModuleColor) -> Self { |
| 29 | Color |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | #[doc(hidden)] |
| 34 | pub struct Canvas { |
| 35 | pic: String, |
| 36 | } |
| 37 | |
| 38 | impl RenderCanvas for Canvas { |
| 39 | type Pixel = Color; |
| 40 | type Image = String; |
| 41 | |
| 42 | fn new(width: u32, height: u32, _dark_pixel: Color, _light_pixel: Color) -> Self { |
| 43 | Canvas { |
| 44 | pic: format!( |
| 45 | concat!( |
| 46 | "maxpswid={w};maxpsht={h};movewid=0;moveht=1;boxwid=1;boxht=1\n", |
| 47 | "define p {{ box wid $3 ht $4 fill 1 with .nw at $1,-$2 }}\n", |
| 48 | "box wid maxpswid ht maxpsht with .nw at 0,0\n", |
| 49 | ), |
| 50 | w = width, |
| 51 | h = height |
| 52 | ), |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | fn draw_dark_pixel(&mut self, x: u32, y: u32) { |
| 57 | self.draw_dark_rect(x, y, 1, 1); |
| 58 | } |
| 59 | |
| 60 | fn draw_dark_rect(&mut self, left: u32, top: u32, width: u32, height: u32) { |
| 61 | writeln!(self.pic, "p({left},{top},{width},{height})").unwrap(); |
| 62 | } |
| 63 | |
| 64 | fn into_image(self) -> String { |
| 65 | self.pic |
| 66 | } |
| 67 | } |