Split Image handling from handwriting/mod.rs

This commit is contained in:
2025-06-23 20:34:02 +02:00
parent 7494dc6b75
commit f2556f7125
2 changed files with 109 additions and 86 deletions

View File

@ -0,0 +1,81 @@
use std::sync::Arc;
use egui::{
Color32, ColorImage, CornerRadius, Painter, Pos2, Rect, Stroke, StrokeKind, TextureHandle,
emath::TSTransform,
epaint::{Brush, RectShape, Vertex},
load::SizedTexture,
};
use crate::rasterizer::rasterize_onto;
use super::StrokeBlendMode;
/// Rasterize onto a resizeable canvas.
#[derive(Default)]
pub struct CanvasRasterizer {
image: ColorImage,
texture: Option<TextureHandle>,
texture_is_dirty: bool,
}
impl CanvasRasterizer {
//pub fn clear(&mut self) {
// self.image = ColorImage::new(self.image.size, Color32::TRANSPARENT);
// self.texture_is_dirty = true;
//}
//pub fn set_size(&mut self, width: usize, height: usize) {
// if self.image.size != [width, height] {
// self.image = ColorImage::new([width, height], Color32::TRANSPARENT);
// self.texture_is_dirty = true;
// }
//}
pub fn clear_and_set_size(&mut self, width: usize, height: usize) {
self.image = ColorImage::new([width, height], Color32::TRANSPARENT);
self.texture_is_dirty = true;
}
pub fn rasterize<'a>(
&mut self,
point_to_pixel: TSTransform,
triangles: impl Iterator<Item = [&'a Vertex; 3]>,
) {
rasterize_onto::<StrokeBlendMode>(&mut self.image, point_to_pixel, triangles);
self.texture_is_dirty = true;
}
pub fn show(&mut self, ctx: &egui::Context, painter: &Painter, at: Rect) {
if self.texture_is_dirty {
self.texture_is_dirty = false;
let new_image = || {
let image = ColorImage::new(self.image.size, Color32::TRANSPARENT);
ctx.load_texture("handwriting", image, Default::default())
};
let texture = self.texture.get_or_insert_with(new_image);
texture.set(self.image.clone(), Default::default());
}
if let Some(texture) = &mut self.texture {
let texture = SizedTexture::new(texture.id(), texture.size_vec2());
let shape = RectShape {
rect: at,
corner_radius: CornerRadius::ZERO,
fill: Color32::WHITE,
stroke: Stroke::NONE,
stroke_kind: StrokeKind::Inside,
round_to_pixels: None,
blur_width: 0.0,
brush: Some(Arc::new(Brush {
fill_texture_id: texture.id,
uv: Rect {
min: Pos2::ZERO,
max: Pos2::new(1.0, 1.0),
},
})),
};
painter.add(shape);
}
}
}