image.rs

 1use crate::{
 2    geometry::{rect::RectF, vector::Vector2F},
 3    json::{json, ToJson},
 4    scene, Border, DebugContext, Element, Event, EventContext, ImageData, LayoutContext,
 5    PaintContext, SizeConstraint,
 6};
 7use std::sync::Arc;
 8
 9use super::constrain_size_preserving_aspect_ratio;
10
11pub struct Image {
12    data: Arc<ImageData>,
13    border: Border,
14    corner_radius: f32,
15}
16
17impl Image {
18    pub fn new(data: Arc<ImageData>) -> Self {
19        Self {
20            data,
21            border: Default::default(),
22            corner_radius: Default::default(),
23        }
24    }
25
26    pub fn with_corner_radius(mut self, corner_radius: f32) -> Self {
27        self.corner_radius = corner_radius;
28        self
29    }
30
31    pub fn with_border(mut self, border: Border) -> Self {
32        self.border = border;
33        self
34    }
35}
36
37impl Element for Image {
38    type LayoutState = ();
39    type PaintState = ();
40
41    fn layout(
42        &mut self,
43        constraint: SizeConstraint,
44        _: &mut LayoutContext,
45    ) -> (Vector2F, Self::LayoutState) {
46        let size =
47            constrain_size_preserving_aspect_ratio(constraint.max, self.data.size().to_f32());
48        (size, ())
49    }
50
51    fn paint(
52        &mut self,
53        bounds: RectF,
54        _: RectF,
55        _: &mut Self::LayoutState,
56        cx: &mut PaintContext,
57    ) -> Self::PaintState {
58        cx.scene.push_image(scene::Image {
59            bounds,
60            border: self.border,
61            corner_radius: self.corner_radius,
62            data: self.data.clone(),
63        });
64    }
65
66    fn dispatch_event(
67        &mut self,
68        _: &Event,
69        _: RectF,
70        _: &mut Self::LayoutState,
71        _: &mut Self::PaintState,
72        _: &mut EventContext,
73    ) -> bool {
74        false
75    }
76
77    fn debug(
78        &self,
79        bounds: RectF,
80        _: &Self::LayoutState,
81        _: &Self::PaintState,
82        _: &DebugContext,
83    ) -> serde_json::Value {
84        json!({
85            "type": "Image",
86            "bounds": bounds.to_json(),
87        })
88    }
89}