image_renderer/pixmap.rs
1//! Pixmap 像素数据视图模块
2//!
3//! 提供对图片像素数据的只读访问
4
5use crate::color::Color;
6use crate::point::IPoint;
7use crate::surface::Surface;
8
9/// Pixmap 像素数据视图
10///
11/// 提供对 Surface 像素数据的只读访问
12pub struct Pixmap<'a> {
13 /// Surface 引用
14 surface: &'a Surface,
15}
16
17impl<'a> Pixmap<'a> {
18 /// 从 Surface 创建 Pixmap
19 pub fn from_surface(surface: &'a Surface) -> Self {
20 Pixmap { surface }
21 }
22
23 /// 获取指定位置的颜色
24 ///
25 /// # 参数
26 ///
27 /// * `point` - 像素坐标点
28 ///
29 /// # 返回值
30 ///
31 /// 返回指定位置的颜色,如果坐标超出范围则返回透明色
32 ///
33 /// # 示例
34 ///
35 /// ```no_run
36 /// use image_renderer::{Surface, IPoint};
37 ///
38 /// let surface = Surface::new(100, 100).unwrap();
39 /// let image = surface.image_snapshot();
40 /// let pixmap = image.peek_pixels();
41 /// let color = pixmap.get_color(IPoint::new(50, 50));
42 /// ```
43 pub fn get_color(&self, point: IPoint) -> Color {
44 if point.x < 0 || point.y < 0 {
45 return Color::TRANSPARENT;
46 }
47
48 let x = point.x as u32;
49 let y = point.y as u32;
50
51 self.surface
52 .get_pixel(x, y)
53 .map(|rgba| Color::from_rgba(rgba))
54 .unwrap_or(Color::TRANSPARENT)
55 }
56
57 /// 获取图片宽度
58 pub fn width(&self) -> u32 {
59 self.surface.width()
60 }
61
62 /// 获取图片高度
63 pub fn height(&self) -> u32 {
64 self.surface.height()
65 }
66
67 /// 获取图片尺寸
68 pub fn dimensions(&self) -> (u32, u32) {
69 self.surface.dimensions()
70 }
71}