Element example

This commit is contained in:
2025-07-01 03:14:36 +02:00
parent 9a626fb1bc
commit da934d9625
5 changed files with 68 additions and 8 deletions
+9
View File
@@ -0,0 +1,9 @@
use crate::widget::Element;
pub struct Rect;
impl Element for Rect {
fn render(&mut self, scope: &mut crate::render::RenderScope) {
scope.draw_rect();
}
}
+24 -7
View File
@@ -1,12 +1,28 @@
pub mod elements;
pub mod render;
pub mod widget;
use std::sync::{Arc, Mutex};
use minifb::Window;
use crate::{render::RenderScope, widget::Element};
pub struct App {
window: Window,
elements: Vec<Arc<Mutex<Box<dyn Element>>>>,
}
impl App {
pub fn new(win: Window) -> Self {
Self { window: win }
Self {
window: win,
elements: Vec::new(),
}
}
pub fn element<E: Element + 'static>(&mut self, e: E) {
self.elements.push(Arc::new(Mutex::new(Box::new(e))));
}
pub fn run(&mut self) {
@@ -17,13 +33,14 @@ impl App {
fn render(&mut self) {
let (w, h) = self.window.get_size();
let mut buffer = vec![0; w * h];
for y in 100..200 {
for x in 150..300 {
buffer[y * h + x] = 0xFF00FF;
}
let mut scope = RenderScope::new(w, h);
for e in &self.elements {
e.lock().unwrap().render(&mut scope);
}
self.window.update_with_buffer(&buffer, w, h).unwrap();
self.window
.update_with_buffer(&scope.get_buffer(), w, h)
.unwrap();
}
}
+3 -1
View File
@@ -1,10 +1,12 @@
use minifb::{Window, WindowOptions};
use osgui::App;
use osgui::{elements::Rect, App};
fn main() {
let window = Window::new("minifb example", 500, 500, WindowOptions::default()).unwrap();
let mut app = App::new(window);
app.element(Rect);
app.run();
}
+27
View File
@@ -0,0 +1,27 @@
pub struct RenderScope {
buffer: Vec<u32>,
width: usize,
height: usize,
}
impl RenderScope {
pub fn new(w: usize, h: usize) -> Self {
Self {
buffer: vec![0; w * h],
width: w,
height: h,
}
}
pub fn draw_rect(&mut self) {
for y in 0..200 {
for x in 0..200 {
self.buffer[y * self.height + x] = 0xFF00FF;
}
}
}
pub fn get_buffer(&self) -> Vec<u32> {
self.buffer.clone()
}
}
+5
View File
@@ -0,0 +1,5 @@
use crate::render::RenderScope;
pub trait Element {
fn render(&mut self, scope: &mut RenderScope);
}