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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
use alloc::{boxed::Box, vec};
use embedded_graphics_core::{prelude::*, primitives::Rectangle};
use crate::utils::center_offset;
/// Canvas on which you can draw but it's not drawable on the display yet.
///
/// Draw on the [`Canvas`] using origin of [`Point::zero()`].
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub struct Canvas<C: PixelColor> {
/// The size of the [`Canvas`].
pub canvas: Size,
/// The pixels of the [`Canvas`].
pub pixels: Box<[Option<C>]>,
}
impl<C: PixelColor> Canvas<C> {
/// Create a new blank [`Canvas`].
///
/// # Panics
///
/// Panics when width * height > [`usize::MAX`].
pub fn new(canvas: Size) -> Self {
Self {
canvas,
pixels: new_pixels(canvas, None),
}
}
/// Create a [`Canvas`] filled with a default color.
///
/// # Panics
///
/// Panics when width * height > [`usize::MAX`].
pub fn with_default_color(canvas: Size, default_color: C) -> Self {
Self {
canvas,
pixels: new_pixels(canvas, default_color.into()),
}
}
/// Helper method that returns the index in the array of pixels
fn point_to_index(&self, point: Point) -> Option<usize> {
point_to_index(self.canvas, Point::zero(), point)
}
fn index_to_point(&self, index: usize) -> Option<Point> {
index_to_point(self.canvas, index)
}
/// Returns the center of [`Size`] of the [`Canvas`].
pub fn center(&self) -> Point {
Point::zero() + center_offset(self.canvas)
}
/// Create a new cropped [`Canvas`].
///
/// This method takes into account the top left [`Point`] of the `area`
/// you'd like to crop relative to the [`Canvas`] itself.
//
/// If the width or height of the [`Rectangle`] is `0`, this method will
/// return [`None`] (see [`Rectangle::bottom_right()`])
// todo: make safer
pub fn crop(&self, area: &Rectangle) -> Option<Canvas<C>> {
let mut new = Canvas::new(area.size);
// returns None when width or height is `0`
// it's safe to return `None` for Canvas too!
let area_bottom_right = area.bottom_right()?;
let new_pixels = self.pixels.iter().enumerate().filter_map(|(index, color)| {
let color = match color {
Some(color) => *color,
None => return None,
};
// Canvas always starts from `Point::zero()`
let point = self.index_to_point(index).unwrap();
// for here on, we should compare the point based on the area we want to crop
if point >= area.top_left && point <= area_bottom_right {
// remove the area top_left to make the origin at `Point::zero()` for the cropped part
let pixel = Pixel(point - area.top_left, color);
Some(pixel)
} else {
None
}
});
new.draw_iter(new_pixels).ok().map(|_| new)
}
/// Sets the place with top left offset where the canvas will be drawn to the display.
pub fn place_at(&self, top_left: Point) -> CanvasAt<C> {
CanvasAt {
top_left,
canvas: self.canvas,
pixels: self.pixels.clone(),
}
}
/// Sets the center of the [`Canvas`] where it will be drawn to the display.
pub fn place_center(&self, center: Point) -> CanvasAt<C> {
let top_left = center - center_offset(self.canvas);
self.place_at(top_left)
}
}
impl<C: PixelColor> OriginDimensions for Canvas<C> {
fn size(&self) -> Size {
self.canvas
}
}
impl<C: PixelColor> DrawTarget for Canvas<C> {
type Color = C;
type Error = core::convert::Infallible;
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
for Pixel(point, color) in pixels.into_iter() {
if let Some(index) = self.point_to_index(point) {
self.pixels[index] = Some(color);
}
}
Ok(())
}
}
/// Canvas which is drawable at the provided [`Point`] (location) on the display.
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[derive(Debug, Clone)]
pub struct CanvasAt<C: PixelColor> {
/// The top left offset where the [`CanvasAt`] will be drawn to the display.
pub top_left: Point,
/// The size of the [`CanvasAt`].
pub canvas: Size,
/// The pixels of the [`CanvasAt`].
pub pixels: Box<[Option<C>]>,
}
impl<C: PixelColor> CanvasAt<C> {
/// Create a new blank [`CanvasAt`].
///
/// # Panics
///
/// Panics when width * height > [`usize::MAX`].
pub fn new(top_left: Point, canvas: Size) -> Self {
let pixels = new_pixels(canvas, None);
Self {
top_left,
canvas,
pixels,
}
}
/// Create a [`CanvasAt`] filled with a default color.
///
/// # Panics
///
/// Panics when width * height > [`usize::MAX`].
pub fn with_default_color(top_left: Point, canvas: Size, default_color: C) -> Self {
let pixel_count = canvas.width as usize * canvas.height as usize;
let pixels = vec![Some(default_color); pixel_count].into_boxed_slice();
Self {
top_left,
canvas,
pixels,
}
}
/// Create a new blank [`CanvasAt`] with a set center on the display.
pub fn with_center(center: Point, canvas: Size) -> Self {
let top_left = center - center_offset(canvas);
Self::new(top_left, canvas)
}
/// Returns the center of the bounding box.
pub fn center(&self) -> Point {
self.bounding_box().center()
}
/// Returns the color of the pixel at a given [`Point`].
///
/// Returns [`None`] if the [`Point`] is outside of the [`CanvasAt`].
pub fn get_pixel(&self, point: Point) -> Option<C> {
self.point_to_index(point)
.and_then(|index| self.pixels.get(index).copied().flatten())
}
/// Helper method that returns the index in the array of pixels
fn point_to_index(&self, point: Point) -> Option<usize> {
point_to_index(self.canvas, self.top_left, point)
}
fn index_to_point(&self, index: usize) -> Option<Point> {
// we account for the displacement of the current Canvas
index_to_point(self.canvas, index).map(|point| point + self.top_left)
}
/// Create a new cropped [`CanvasAt`].
///
/// This method takes into account the top left [`Point`] of the `area`
/// you'd like to crop relative to the **display**.
///
/// If the width or height of the [`Rectangle`] is `0`, this method will
/// return [`None`] (see [`Rectangle::bottom_right()`])
// todo: make safer
pub fn crop(&self, area: &Rectangle) -> Option<CanvasAt<C>> {
let mut new = CanvasAt::new(area.top_left, area.size);
// returns None when width or height is `0`
// it's safe to return `None` for Canvas too!
let area_bottom_right = area.bottom_right()?;
let new_pixels = self.pixels.iter().enumerate().filter_map(|(index, color)| {
let color = match color {
Some(color) => *color,
None => return None,
};
let point = self.index_to_point(index).expect("Will never fail");
// for here on, we should compare the point based on the area we want to crop
if point >= area.top_left && point <= area_bottom_right {
let pixel = Pixel(point, color);
Some(pixel)
} else {
None
}
});
new.draw_iter(new_pixels).ok().map(|_| new)
}
}
impl<C: PixelColor> Dimensions for CanvasAt<C> {
fn bounding_box(&self) -> Rectangle {
Rectangle::new(self.top_left, self.canvas)
}
}
impl<C: PixelColor> DrawTarget for CanvasAt<C> {
type Color = C;
type Error = core::convert::Infallible;
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
for Pixel(point, color) in pixels.into_iter() {
if let Some(index) = self.point_to_index(point) {
self.pixels[index] = Some(color);
}
}
Ok(())
}
}
impl<C> Drawable for CanvasAt<C>
where
C: PixelColor,
{
type Color = C;
type Output = ();
fn draw<D>(&self, target: &mut D) -> Result<Self::Output, D::Error>
where
D: DrawTarget<Color = C>,
{
let pixels_iter = self.bounding_box().points().filter_map(|point| {
// for the drawing position we need to account for the top_left offset of the drawn display
self.get_pixel(point).map(|color| Pixel(point, color))
});
target.draw_iter(pixels_iter)
}
}
#[cfg(feature = "transform")]
#[cfg_attr(docsrs, doc(cfg(feature = "transform")))]
impl<C: PixelColor> embedded_graphics::transform::Transform for CanvasAt<C> {
fn translate(&self, by: Point) -> Self {
Self {
// update the CanvasAt top_left!
top_left: self.top_left + by,
canvas: self.canvas,
pixels: self.pixels.clone(),
}
}
fn translate_mut(&mut self, by: Point) -> &mut Self {
self.top_left += by;
self
}
}
/// Generic function that will take into account the top_left offset when returning the index
// TODO: make safer
fn point_to_index(size: Size, top_left_offset: Point, point: Point) -> Option<usize> {
// we must account for the top_left corner of the drawing box
if let Ok((x, y)) = <(u32, u32)>::try_from(point - top_left_offset) {
if x < size.width && y < size.height {
return Some((x + y * size.width) as usize);
}
}
None
}
fn index_to_point(size: Size, index: usize) -> Option<Point> {
let x = index as i32 % size.width as i32;
let y = index as i32 / size.width as i32;
let point = Point { x, y };
Some(point)
}
fn new_pixels<C: PixelColor>(size: Size, color: Option<C>) -> Box<[Option<C>]> {
let pixel_count = size.width as usize * size.height as usize;
vec![color; pixel_count].into_boxed_slice()
}
#[cfg(test)]
mod test {
use embedded_graphics_core::pixelcolor::BinaryColor;
use super::*;
#[test]
fn test_index_to_point() {
let canvas = Canvas::<BinaryColor>::new(Size {
width: 320,
height: 240,
});
{
let center = Point::new(160, 120);
let center_index = canvas.point_to_index(center).expect("Inside the canvas");
assert_eq!(
center,
canvas
.index_to_point(center_index)
.expect("Should fetch the index")
);
}
{
let bottom_right = Point::new(320 - 1, 240 - 1);
let br_index = canvas
.point_to_index(bottom_right)
.expect("Inside the canvas");
assert_eq!(
bottom_right,
canvas
.index_to_point(br_index)
.expect("Should fetch the index")
);
}
{
let top_left = Point::new(0, 0);
let tl_index = canvas.point_to_index(top_left).expect("Inside the canvas");
assert_eq!(
top_left,
canvas
.index_to_point(tl_index)
.expect("Should fetch the index")
);
}
{
let bottom_left = Point::new(0, 240 - 1);
let bl_index = canvas
.point_to_index(bottom_left)
.expect("Inside the canvas");
assert_eq!(
bottom_left,
canvas
.index_to_point(bl_index)
.expect("Should fetch the index")
);
}
{
let top_right = Point::new(320 - 1, 0);
let tr_index = canvas.point_to_index(top_right).expect("Inside the canvas");
assert_eq!(
top_right,
canvas
.index_to_point(tr_index)
.expect("Should fetch the index")
);
}
}
}