Expand description
Winit allows you to build a window on as many platforms as possible.
Building a window
Before you can build a window, you first need to build an EventsLoop
. This is done with the
EventsLoop::new()
function. Example:
use winit::EventsLoop;
let events_loop = EventsLoop::new();
Once this is done there are two ways to create a window:
- Calling
Window::new(&events_loop)
. - Calling
let builder = WindowBuilder::new()
thenbuilder.build(&events_loop)
.
The first way is the simplest way and will give you default values for everything.
The second way allows you to customize the way your window will look and behave by modifying
the fields of the WindowBuilder
object before you create the window.
Events handling
Once a window has been created, it will generate events. For example whenever the user moves the window, resizes the window, moves the mouse, etc. an event is generated.
The events generated by a window can be retrieved from the EventsLoop
the window was created
with.
There are two ways to do so. The first is to call events_loop.poll_events(...)
, which will
retrieve all the events pending on the windows and immediately return after no new event is
available. You usually want to use this method in application that render continuously on the
screen, such as video games.
use winit::{Event, WindowEvent};
use winit::dpi::LogicalSize;
loop {
events_loop.poll_events(|event| {
match event {
Event::WindowEvent {
event: WindowEvent::Resized(LogicalSize { width, height }),
..
} => {
println!("The window was resized to {}x{}", width, height);
},
_ => ()
}
});
}
The second way is to call events_loop.run_forever(...)
. As its name tells, it will run
forever unless it is stopped by returning ControlFlow::Break
.
use winit::{ControlFlow, Event, WindowEvent};
events_loop.run_forever(|event| {
match event {
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
println!("The close button was pressed; stopping");
ControlFlow::Break
},
_ => ControlFlow::Continue,
}
});
If you use multiple windows, the WindowEvent
event has a member named window_id
. You can
compare it with the value returned by the id()
method of Window
in order to know which
window has received the event.
Drawing on the window
Winit doesn’t provide any function that allows drawing on a window. However it allows you to
retrieve the raw handle of the window (see the os
module for that), which in turn allows you
to create an OpenGL/Vulkan/DirectX/Metal/etc. context that will draw on the window.
Modules
Structs
EventsLoopProxy
attempts to wake up an EventsLoop
that
no longer exists.EventsLoop
from another thread.Enums
Icon::from_rgba
with invalid arguments.EventsLoop::run_forever
method.Window
.