iced_widget/image/
viewer.rs

1//! Zoom and pan on an image.
2use crate::core::border;
3use crate::core::image::{self, FilterMethod};
4use crate::core::layout;
5use crate::core::mouse;
6use crate::core::renderer;
7use crate::core::widget::tree::{self, Tree};
8use crate::core::{
9    Clipboard, ContentFit, Element, Event, Image, Layout, Length, Pixels,
10    Point, Radians, Rectangle, Shell, Size, Vector, Widget,
11};
12
13/// A frame that displays an image with the ability to zoom in/out and pan.
14pub struct Viewer<Handle> {
15    padding: f32,
16    width: Length,
17    height: Length,
18    min_scale: f32,
19    max_scale: f32,
20    scale_step: f32,
21    handle: Handle,
22    filter_method: FilterMethod,
23    content_fit: ContentFit,
24}
25
26impl<Handle> Viewer<Handle> {
27    /// Creates a new [`Viewer`] with the given [`State`].
28    pub fn new<T: Into<Handle>>(handle: T) -> Self {
29        Viewer {
30            handle: handle.into(),
31            padding: 0.0,
32            width: Length::Shrink,
33            height: Length::Shrink,
34            min_scale: 0.25,
35            max_scale: 10.0,
36            scale_step: 0.10,
37            filter_method: FilterMethod::default(),
38            content_fit: ContentFit::default(),
39        }
40    }
41
42    /// Sets the [`FilterMethod`] of the [`Viewer`].
43    pub fn filter_method(mut self, filter_method: image::FilterMethod) -> Self {
44        self.filter_method = filter_method;
45        self
46    }
47
48    /// Sets the [`ContentFit`] of the [`Viewer`].
49    pub fn content_fit(mut self, content_fit: ContentFit) -> Self {
50        self.content_fit = content_fit;
51        self
52    }
53
54    /// Sets the padding of the [`Viewer`].
55    pub fn padding(mut self, padding: impl Into<Pixels>) -> Self {
56        self.padding = padding.into().0;
57        self
58    }
59
60    /// Sets the width of the [`Viewer`].
61    pub fn width(mut self, width: impl Into<Length>) -> Self {
62        self.width = width.into();
63        self
64    }
65
66    /// Sets the height of the [`Viewer`].
67    pub fn height(mut self, height: impl Into<Length>) -> Self {
68        self.height = height.into();
69        self
70    }
71
72    /// Sets the max scale applied to the image of the [`Viewer`].
73    ///
74    /// Default is `10.0`
75    pub fn max_scale(mut self, max_scale: f32) -> Self {
76        self.max_scale = max_scale;
77        self
78    }
79
80    /// Sets the min scale applied to the image of the [`Viewer`].
81    ///
82    /// Default is `0.25`
83    pub fn min_scale(mut self, min_scale: f32) -> Self {
84        self.min_scale = min_scale;
85        self
86    }
87
88    /// Sets the percentage the image of the [`Viewer`] will be scaled by
89    /// when zoomed in / out.
90    ///
91    /// Default is `0.10`
92    pub fn scale_step(mut self, scale_step: f32) -> Self {
93        self.scale_step = scale_step;
94        self
95    }
96}
97
98impl<Message, Theme, Renderer, Handle> Widget<Message, Theme, Renderer>
99    for Viewer<Handle>
100where
101    Renderer: image::Renderer<Handle = Handle>,
102    Handle: Clone,
103{
104    fn tag(&self) -> tree::Tag {
105        tree::Tag::of::<State>()
106    }
107
108    fn state(&self) -> tree::State {
109        tree::State::new(State::new())
110    }
111
112    fn size(&self) -> Size<Length> {
113        Size {
114            width: self.width,
115            height: self.height,
116        }
117    }
118
119    fn layout(
120        &mut self,
121        _tree: &mut Tree,
122        renderer: &Renderer,
123        limits: &layout::Limits,
124    ) -> layout::Node {
125        // The raw w/h of the underlying image
126        let image_size =
127            renderer.measure_image(&self.handle).unwrap_or_default();
128
129        let image_size =
130            Size::new(image_size.width as f32, image_size.height as f32);
131
132        // The size to be available to the widget prior to `Shrink`ing
133        let raw_size = limits.resolve(self.width, self.height, image_size);
134
135        // The uncropped size of the image when fit to the bounds above
136        let full_size = self.content_fit.fit(image_size, raw_size);
137
138        // Shrink the widget to fit the resized image, if requested
139        let final_size = Size {
140            width: match self.width {
141                Length::Shrink => f32::min(raw_size.width, full_size.width),
142                _ => raw_size.width,
143            },
144            height: match self.height {
145                Length::Shrink => f32::min(raw_size.height, full_size.height),
146                _ => raw_size.height,
147            },
148        };
149
150        layout::Node::new(final_size)
151    }
152
153    fn update(
154        &mut self,
155        tree: &mut Tree,
156        event: &Event,
157        layout: Layout<'_>,
158        cursor: mouse::Cursor,
159        renderer: &Renderer,
160        _clipboard: &mut dyn Clipboard,
161        shell: &mut Shell<'_, Message>,
162        _viewport: &Rectangle,
163    ) {
164        let bounds = layout.bounds();
165
166        match event {
167            Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
168                let Some(cursor_position) = cursor.position_over(bounds) else {
169                    return;
170                };
171
172                match *delta {
173                    mouse::ScrollDelta::Lines { y, .. }
174                    | mouse::ScrollDelta::Pixels { y, .. } => {
175                        let state = tree.state.downcast_mut::<State>();
176                        let previous_scale = state.scale;
177
178                        if y < 0.0 && previous_scale > self.min_scale
179                            || y > 0.0 && previous_scale < self.max_scale
180                        {
181                            state.scale = (if y > 0.0 {
182                                state.scale * (1.0 + self.scale_step)
183                            } else {
184                                state.scale / (1.0 + self.scale_step)
185                            })
186                            .clamp(self.min_scale, self.max_scale);
187
188                            let scaled_size = scaled_image_size(
189                                renderer,
190                                &self.handle,
191                                state,
192                                bounds.size(),
193                                self.content_fit,
194                            );
195
196                            let factor = state.scale / previous_scale - 1.0;
197
198                            let cursor_to_center =
199                                cursor_position - bounds.center();
200
201                            let adjustment = cursor_to_center * factor
202                                + state.current_offset * factor;
203
204                            state.current_offset = Vector::new(
205                                if scaled_size.width > bounds.width {
206                                    state.current_offset.x + adjustment.x
207                                } else {
208                                    0.0
209                                },
210                                if scaled_size.height > bounds.height {
211                                    state.current_offset.y + adjustment.y
212                                } else {
213                                    0.0
214                                },
215                            );
216                        }
217                    }
218                }
219
220                shell.request_redraw();
221                shell.capture_event();
222            }
223            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
224                let Some(cursor_position) = cursor.position_over(bounds) else {
225                    return;
226                };
227
228                let state = tree.state.downcast_mut::<State>();
229
230                state.cursor_grabbed_at = Some(cursor_position);
231                state.starting_offset = state.current_offset;
232
233                shell.capture_event();
234            }
235            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
236                let state = tree.state.downcast_mut::<State>();
237
238                state.cursor_grabbed_at = None;
239            }
240            Event::Mouse(mouse::Event::CursorMoved { position }) => {
241                let state = tree.state.downcast_mut::<State>();
242
243                if let Some(origin) = state.cursor_grabbed_at {
244                    let scaled_size = scaled_image_size(
245                        renderer,
246                        &self.handle,
247                        state,
248                        bounds.size(),
249                        self.content_fit,
250                    );
251                    let hidden_width = (scaled_size.width - bounds.width / 2.0)
252                        .max(0.0)
253                        .round();
254
255                    let hidden_height = (scaled_size.height
256                        - bounds.height / 2.0)
257                        .max(0.0)
258                        .round();
259
260                    let delta = *position - origin;
261
262                    let x = if bounds.width < scaled_size.width {
263                        (state.starting_offset.x - delta.x)
264                            .clamp(-hidden_width, hidden_width)
265                    } else {
266                        0.0
267                    };
268
269                    let y = if bounds.height < scaled_size.height {
270                        (state.starting_offset.y - delta.y)
271                            .clamp(-hidden_height, hidden_height)
272                    } else {
273                        0.0
274                    };
275
276                    state.current_offset = Vector::new(x, y);
277                    shell.request_redraw();
278                    shell.capture_event();
279                }
280            }
281            _ => {}
282        }
283    }
284
285    fn mouse_interaction(
286        &self,
287        tree: &Tree,
288        layout: Layout<'_>,
289        cursor: mouse::Cursor,
290        _viewport: &Rectangle,
291        _renderer: &Renderer,
292    ) -> mouse::Interaction {
293        let state = tree.state.downcast_ref::<State>();
294        let bounds = layout.bounds();
295        let is_mouse_over = cursor.is_over(bounds);
296
297        if state.is_cursor_grabbed() {
298            mouse::Interaction::Grabbing
299        } else if is_mouse_over {
300            mouse::Interaction::Grab
301        } else {
302            mouse::Interaction::None
303        }
304    }
305
306    fn draw(
307        &self,
308        tree: &Tree,
309        renderer: &mut Renderer,
310        _theme: &Theme,
311        _style: &renderer::Style,
312        layout: Layout<'_>,
313        _cursor: mouse::Cursor,
314        viewport: &Rectangle,
315    ) {
316        let state = tree.state.downcast_ref::<State>();
317        let bounds = layout.bounds();
318
319        let final_size = scaled_image_size(
320            renderer,
321            &self.handle,
322            state,
323            bounds.size(),
324            self.content_fit,
325        );
326
327        let translation = {
328            let diff_w = bounds.width - final_size.width;
329            let diff_h = bounds.height - final_size.height;
330
331            let image_top_left = match self.content_fit {
332                ContentFit::None => {
333                    Vector::new(diff_w.max(0.0) / 2.0, diff_h.max(0.0) / 2.0)
334                }
335                _ => Vector::new(diff_w / 2.0, diff_h / 2.0),
336            };
337
338            image_top_left - state.offset(bounds, final_size)
339        };
340
341        let drawing_bounds = Rectangle::new(bounds.position(), final_size);
342
343        let render = |renderer: &mut Renderer| {
344            renderer.with_translation(translation, |renderer| {
345                renderer.draw_image(
346                    Image {
347                        handle: self.handle.clone(),
348                        border_radius: border::Radius::default(),
349                        filter_method: self.filter_method,
350                        rotation: Radians(0.0),
351                        opacity: 1.0,
352                        snap: true,
353                    },
354                    drawing_bounds,
355                    *viewport,
356                );
357            });
358        };
359
360        renderer.with_layer(bounds, render);
361    }
362}
363
364/// The local state of a [`Viewer`].
365#[derive(Debug, Clone, Copy)]
366pub struct State {
367    scale: f32,
368    starting_offset: Vector,
369    current_offset: Vector,
370    cursor_grabbed_at: Option<Point>,
371}
372
373impl Default for State {
374    fn default() -> Self {
375        Self {
376            scale: 1.0,
377            starting_offset: Vector::default(),
378            current_offset: Vector::default(),
379            cursor_grabbed_at: None,
380        }
381    }
382}
383
384impl State {
385    /// Creates a new [`State`].
386    pub fn new() -> Self {
387        State::default()
388    }
389
390    /// Returns the current offset of the [`State`], given the bounds
391    /// of the [`Viewer`] and its image.
392    fn offset(&self, bounds: Rectangle, image_size: Size) -> Vector {
393        let hidden_width =
394            (image_size.width - bounds.width / 2.0).max(0.0).round();
395
396        let hidden_height =
397            (image_size.height - bounds.height / 2.0).max(0.0).round();
398
399        Vector::new(
400            self.current_offset.x.clamp(-hidden_width, hidden_width),
401            self.current_offset.y.clamp(-hidden_height, hidden_height),
402        )
403    }
404
405    /// Returns if the cursor is currently grabbed by the [`Viewer`].
406    pub fn is_cursor_grabbed(&self) -> bool {
407        self.cursor_grabbed_at.is_some()
408    }
409}
410
411impl<'a, Message, Theme, Renderer, Handle> From<Viewer<Handle>>
412    for Element<'a, Message, Theme, Renderer>
413where
414    Renderer: 'a + image::Renderer<Handle = Handle>,
415    Message: 'a,
416    Handle: Clone + 'a,
417{
418    fn from(viewer: Viewer<Handle>) -> Element<'a, Message, Theme, Renderer> {
419        Element::new(viewer)
420    }
421}
422
423/// Returns the bounds of the underlying image, given the bounds of
424/// the [`Viewer`]. Scaling will be applied and original aspect ratio
425/// will be respected.
426pub fn scaled_image_size<Renderer>(
427    renderer: &Renderer,
428    handle: &<Renderer as image::Renderer>::Handle,
429    state: &State,
430    bounds: Size,
431    content_fit: ContentFit,
432) -> Size
433where
434    Renderer: image::Renderer,
435{
436    let Size { width, height } =
437        renderer.measure_image(handle).unwrap_or_default();
438
439    let image_size = Size::new(width as f32, height as f32);
440
441    let adjusted_fit = content_fit.fit(image_size, bounds);
442
443    Size::new(
444        adjusted_fit.width * state.scale,
445        adjusted_fit.height * state.scale,
446    )
447}