use crate::paint::{PaintCommand, PaintList, Vertex};
use crate::{Color, Point, Rect, Size};
pub struct Painter<'a> {
list: &'a mut PaintList,
origin: Point,
size: Size,
clip_depth: usize,
}
impl<'a> Painter<'a> {
pub fn new(list: &'a mut PaintList, origin: Point, size: Size) -> Self {
Self { list, origin, size, clip_depth: 0 }
}
pub fn bounds(&self) -> Rect {
Rect::new(0.0, 0.0, self.size.width, self.size.height)
}
fn local_rect(&self, rect: Rect) -> Rect {
Rect::new(rect.x + self.origin.x, rect.y + self.origin.y, rect.width, rect.height)
}
fn local_point(&self, point: Point) -> Point {
Point::new(point.x + self.origin.x, point.y + self.origin.y)
}
pub fn rect(&mut self, rect: Rect, color: Color) {
self.list.rect(self.local_rect(rect), color);
}
pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
self.list.rounded_rect(self.local_rect(rect), color, radius);
}
pub fn linear_gradient(
&mut self,
rect: Rect,
start: Point,
end: Point,
from: Color,
to: Color,
corner_radius: f32,
) {
self.list.linear_gradient(
self.local_rect(rect),
self.local_point(start),
self.local_point(end),
from,
to,
corner_radius,
);
}
pub fn radial_gradient(
&mut self,
rect: Rect,
center: Point,
radial_radius: f32,
from: Color,
to: Color,
corner_radius: f32,
) {
self.list.radial_gradient(
self.local_rect(rect),
self.local_point(center),
radial_radius,
from,
to,
corner_radius,
);
}
pub fn triangles(&mut self, vertices: Vec<Vertex>, indices: Vec<u32>) {
let shifted: Vec<Vertex> = vertices
.into_iter()
.map(|mut v| {
v.x += self.origin.x;
v.y += self.origin.y;
v
})
.collect();
self.list.commands.push(PaintCommand::Triangles { vertices: shifted, indices });
}
pub fn text(&mut self, text: impl Into<std::rc::Rc<str>>, font_size: f32, color: Color, position: Point) {
self.list.text(text, font_size, color, self.local_point(position));
}
pub fn text_wrapped(
&mut self,
text: impl Into<std::rc::Rc<str>>,
font_size: f32,
color: Color,
position: Point,
max_width: Option<f32>,
) {
self.list.text_wrapped(text, font_size, color, self.local_point(position), max_width);
}
pub fn push_clip(&mut self, rect: Rect) {
self.list.commands.push(PaintCommand::PushClip(self.local_rect(rect)));
self.clip_depth += 1;
}
pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
self.list.commands.push(PaintCommand::PushClipRRect { rect: self.local_rect(rect), radius });
self.clip_depth += 1;
}
pub fn pop_clip(&mut self) -> bool {
if self.clip_depth == 0 {
return false;
}
self.list.commands.push(PaintCommand::PopClip);
self.clip_depth -= 1;
true
}
pub fn close_clips(&mut self) {
while self.clip_depth > 0 {
self.list.commands.push(PaintCommand::PopClip);
self.clip_depth -= 1;
}
}
pub fn clip_depth(&self) -> usize {
self.clip_depth
}
}