Add scale_factor to Application and Sandbox

This commit is contained in:
Héctor Ramón Jiménez 2020-06-19 19:17:05 +02:00
parent d19c02035f
commit c9696ca687
4 changed files with 93 additions and 5 deletions

View file

@ -84,6 +84,21 @@ pub trait Application: Program {
fn background_color(&self) -> Color {
Color::WHITE
}
/// Returns the scale factor of the [`Application`].
///
/// It can be used to dynamically control the size of the UI at runtime
/// (i.e. zooming).
///
/// For instance, a scale factor of `2.0` will make widgets twice as big,
/// while a scale factor of `0.5` will shrink them to half their size.
///
/// By default, it returns `1.0`.
///
/// [`Application`]: trait.Application.html
fn scale_factor(&self) -> f64 {
1.0
}
}
/// Runs an [`Application`] with an executor, compositor, and the provided
@ -124,6 +139,7 @@ pub fn run<A, E, C>(
let mut title = application.title();
let mut mode = application.mode();
let mut background_color = application.background_color();
let mut scale_factor = application.scale_factor();
let window = settings
.window
@ -138,7 +154,7 @@ pub fn run<A, E, C>(
let physical_size = window.inner_size();
let mut viewport = Viewport::with_physical_size(
Size::new(physical_size.width, physical_size.height),
window.scale_factor(),
window.scale_factor() * scale_factor,
);
let mut resized = false;
@ -208,6 +224,20 @@ pub fn run<A, E, C>(
// Update background color
background_color = program.background_color();
// Update scale factor
let new_scale_factor = program.scale_factor();
if scale_factor != new_scale_factor {
let size = window.inner_size();
viewport = Viewport::with_physical_size(
Size::new(size.width, size.height),
window.scale_factor() * new_scale_factor,
);
scale_factor = new_scale_factor;
}
}
window.request_redraw();
@ -259,6 +289,7 @@ pub fn run<A, E, C>(
handle_window_event(
&window_event,
&window,
scale_factor,
control_flow,
&mut modifiers,
&mut viewport,
@ -286,6 +317,7 @@ pub fn run<A, E, C>(
pub fn handle_window_event(
event: &winit::event::WindowEvent<'_>,
window: &winit::window::Window,
scale_factor: f64,
control_flow: &mut winit::event_loop::ControlFlow,
modifiers: &mut winit::event::ModifiersState,
viewport: &mut Viewport,
@ -298,8 +330,10 @@ pub fn handle_window_event(
WindowEvent::Resized(new_size) => {
let size = Size::new(new_size.width, new_size.height);
*viewport =
Viewport::with_physical_size(size, window.scale_factor());
*viewport = Viewport::with_physical_size(
size,
window.scale_factor() * scale_factor,
);
*resized = true;
}
WindowEvent::CloseRequested => {