diff options
author | 2024-04-30 08:06:51 +0200 | |
---|---|---|
committer | 2024-04-30 08:06:51 +0200 | |
commit | 3c7b43d031a06d59afbba83bc9d088517c096f20 (patch) | |
tree | 44dd209749fd9e9b2bfac0e85df9a36aec5056dc /examples/the_matrix | |
parent | b5b78d505e22cafccb4ecbf57dc61f536ca558ca (diff) | |
download | iced-3c7b43d031a06d59afbba83bc9d088517c096f20.tar.gz iced-3c7b43d031a06d59afbba83bc9d088517c096f20.tar.bz2 iced-3c7b43d031a06d59afbba83bc9d088517c096f20.zip |
Use shared `Cache` group in `the_matrix` example
Diffstat (limited to 'examples/the_matrix')
-rw-r--r-- | examples/the_matrix/src/main.rs | 32 |
1 files changed, 17 insertions, 15 deletions
diff --git a/examples/the_matrix/src/main.rs b/examples/the_matrix/src/main.rs index 55c9da4b..97ad31b9 100644 --- a/examples/the_matrix/src/main.rs +++ b/examples/the_matrix/src/main.rs @@ -1,12 +1,13 @@ use iced::mouse; use iced::time::{self, Instant}; use iced::widget::canvas; -use iced::widget::canvas::{Cache, Geometry}; use iced::{ Color, Element, Font, Length, Point, Rectangle, Renderer, Subscription, Theme, }; +use std::cell::RefCell; + pub fn main() -> iced::Result { iced::program("The Matrix - Iced", TheMatrix::update, TheMatrix::view) .subscription(TheMatrix::subscription) @@ -15,8 +16,7 @@ pub fn main() -> iced::Result { } struct TheMatrix { - ticks: usize, - backgrounds: Vec<Cache>, + tick: usize, } #[derive(Debug, Clone, Copy)] @@ -28,7 +28,7 @@ impl TheMatrix { fn update(&mut self, message: Message) { match message { Message::Tick(_now) => { - self.ticks += 1; + self.tick += 1; } } } @@ -47,33 +47,35 @@ impl TheMatrix { impl Default for TheMatrix { fn default() -> Self { - let mut backgrounds = Vec::with_capacity(30); - backgrounds.resize_with(30, Cache::default); - - Self { - ticks: 0, - backgrounds, - } + Self { tick: 0 } } } impl<Message> canvas::Program<Message> for TheMatrix { - type State = (); + type State = RefCell<Vec<canvas::Cache>>; fn draw( &self, - _state: &Self::State, + state: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: mouse::Cursor, - ) -> Vec<Geometry> { + ) -> Vec<canvas::Geometry> { use rand::distributions::Distribution; use rand::Rng; const CELL_SIZE: f32 = 10.0; - vec![self.backgrounds[self.ticks % self.backgrounds.len()].draw( + let mut caches = state.borrow_mut(); + + if caches.is_empty() { + let group = canvas::Group::unique(); + + caches.resize_with(30, || canvas::Cache::with_group(group)); + } + + vec![caches[self.tick % caches.len()].draw( renderer, bounds.size(), |frame| { |