Add egui::Scene for panning/zooming a Ui (#5505)

This is similar to `ScrollArea`, but:
* Supports zooming
* Has no scroll bars
* Has no limits on the scrolling

## TODO
* [x] Automatic sizing of `Scene`s outer bounds
* [x] Fix text selection in scenes
* [x] Implement `fit_rect`
* [x] Document / improve API

---------

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
This commit is contained in:
Jochen Görtler
2025-01-28 20:06:10 +01:00
committed by GitHub
co-authored by Emil Ernerfeldt
parent 37c564be2c
commit e8f351b729
13 changed files with 391 additions and 189 deletions
+82
View File
@@ -0,0 +1,82 @@
use egui::{Pos2, Rect, Scene, Vec2};
use super::widget_gallery;
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SceneDemo {
widget_gallery: widget_gallery::WidgetGallery,
scene_rect: Rect,
}
impl Default for SceneDemo {
fn default() -> Self {
Self {
widget_gallery: Default::default(),
scene_rect: Rect::ZERO, // `egui::Scene` will initialize this to something valid
}
}
}
impl crate::Demo for SceneDemo {
fn name(&self) -> &'static str {
"🔍 Scene"
}
fn show(&mut self, ctx: &egui::Context, open: &mut bool) {
use crate::View as _;
let window = egui::Window::new("Scene")
.default_width(300.0)
.default_height(300.0)
.scroll(false)
.open(open);
window.show(ctx, |ui| self.ui(ui));
}
}
impl crate::View for SceneDemo {
fn ui(&mut self, ui: &mut egui::Ui) {
ui.label(
"You can pan by scrolling, and zoom using cmd-scroll. \
Double click on the background to reset view.",
);
ui.vertical_centered(|ui| {
ui.add(crate::egui_github_link_file!());
});
ui.separator();
ui.label(format!("Scene rect: {:#?}", &mut self.scene_rect));
ui.separator();
egui::Frame::group(ui.style())
.inner_margin(0.0)
.show(ui, |ui| {
let scene = Scene::new()
.max_inner_size([350.0, 1000.0])
.zoom_range(0.1..=2.0);
let mut reset_view = false;
let mut inner_rect = Rect::NAN;
let response = scene
.show(ui, &mut self.scene_rect, |ui| {
reset_view = ui.button("Reset view").clicked();
ui.add_space(16.0);
self.widget_gallery.ui(ui);
ui.put(
Rect::from_min_size(Pos2::new(0.0, -64.0), Vec2::new(200.0, 16.0)),
egui::Label::new("You can put a widget anywhere").selectable(false),
);
inner_rect = ui.min_rect();
})
.response;
if reset_view || response.double_clicked() {
self.scene_rect = inner_rect;
}
});
}
}