1use taffy::{AvailableSpace, Size, Style};
2
3use super::Styled;
4use crate::render::{Bitmap, Color};
5use crate::text::Text;
6use crate::widget::{Element, PaintCx, Widget};
7
8pub struct Image {
10 bitmap: Bitmap,
11 radius: f32,
12 tint: Color,
13 style: Style,
14}
15
16#[doc = example!("image")]
19pub fn image(bitmap: Bitmap) -> Image {
20 let aspect = bitmap.width() as f32 / bitmap.height().max(1) as f32;
21 Image {
22 bitmap,
23 radius: 0.0,
24 tint: Color::WHITE,
25 style: Style {
26 aspect_ratio: Some(aspect),
27 ..Style::default()
28 },
29 }
30}
31
32impl Image {
33 pub fn radius(mut self, r: f32) -> Self {
35 self.radius = r;
36 self
37 }
38 pub fn tint(mut self, c: Color) -> Self {
40 self.tint = c;
41 self
42 }
43}
44
45impl From<Image> for Element {
46 fn from(w: Image) -> Self {
47 Element::new(w)
48 }
49}
50
51impl Styled for Image {
52 fn style_mut(&mut self) -> &mut Style {
53 &mut self.style
54 }
55}
56
57impl Widget for Image {
58 fn style(&self) -> Style {
59 self.style.clone()
60 }
61 fn measure(
62 &self,
63 known: Size<Option<f32>>,
64 _available: Size<AvailableSpace>,
65 _text: &Text,
66 ) -> Size<f32> {
67 let (w, h) = (self.bitmap.width() as f32, self.bitmap.height() as f32);
68 match (known.width, known.height) {
69 (Some(kw), Some(kh)) => Size {
70 width: kw,
71 height: kh,
72 },
73 (Some(kw), None) => Size {
74 width: kw,
75 height: kw * h / w.max(1.0),
76 },
77 (None, Some(kh)) => Size {
78 width: kh * w / h.max(1.0),
79 height: kh,
80 },
81 (None, None) => Size {
82 width: w,
83 height: h,
84 },
85 }
86 }
87 fn measure_key(&self) -> u64 {
88 (self.bitmap.width() as u64) << 32 | self.bitmap.height() as u64
89 }
90 fn paint(&self, cx: &mut PaintCx) {
91 cx.image(cx.rect, &self.bitmap, self.radius, self.tint);
92 }
93}