Skip to main content

yog_graphics/
image.rs

1//! RGBA images.
2
3use yog_data::Schema;
4
5use crate::color::Color;
6
7/// Pixels, RGBA8 row by row from the top, straight alpha.
8#[derive(Schema, Debug, Clone, PartialEq, Default)]
9pub struct Image {
10    pub width: u32,
11    pub height: u32,
12    pub rgba: Vec<u8>,
13}
14
15impl Image {
16    /// A transparent `width × height` image.
17    pub fn new(width: u32, height: u32) -> Image {
18        Image { width, height, rgba: vec![0; (width * height * 4) as usize] }
19    }
20
21    pub fn is_empty(&self) -> bool {
22        self.width == 0 || self.height == 0
23    }
24
25    fn index(&self, x: u32, y: u32) -> usize {
26        ((y * self.width + x) * 4) as usize
27    }
28
29    pub fn pixel(&self, x: u32, y: u32) -> Color {
30        let i = self.index(x, y);
31        Color::from_rgba8([self.rgba[i], self.rgba[i + 1], self.rgba[i + 2], self.rgba[i + 3]])
32    }
33
34    pub fn set_pixel(&mut self, x: u32, y: u32, c: Color) {
35        let i = self.index(x, y);
36        self.rgba[i..i + 4].copy_from_slice(&c.to_rgba8());
37    }
38}
39
40/// An image and where it goes: its top-left corner `x, y` pixels (`y`
41/// down) from the origin it was drawn for — a glyph's from its pen
42/// position on the baseline, say.
43#[derive(Debug, Clone, PartialEq, Default)]
44pub struct PlacedImage {
45    pub image: Image,
46    pub x: i32,
47    pub y: i32,
48}