use druid::kurbo::BezPath;
use druid::piet::{FontBuilder, ImageFormat, InterpolationMode, Text, TextLayoutBuilder};
use druid::{
Affine, AppLauncher, BoxConstraints, Color, Env, Event, EventCtx, LayoutCtx, PaintCtx, Point,
Rect, RenderContext, Size, UpdateCtx, Widget, WindowDesc,
};
struct CustomWidget;
impl Widget<String> for CustomWidget {
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut String, _env: &Env) {}
fn update(
&mut self,
_ctx: &mut UpdateCtx,
_old_data: Option<&String>,
_data: &String,
_env: &Env,
) {
}
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &String,
_env: &Env,
) -> Size {
bc.max()
}
fn paint(&mut self, paint_ctx: &mut PaintCtx, data: &String, _env: &Env) {
paint_ctx.clear(Color::WHITE);
let size = paint_ctx.size();
let mut path = BezPath::new();
path.move_to(Point::ORIGIN);
path.quad_to((80.0, 90.0), (size.width, size.height));
let stroke_color = Color::rgb8(0x00, 0x80, 0x00);
paint_ctx.stroke(path, &stroke_color, 1.0);
let rect = Rect::from_origin_size((10., 10.), (100., 100.));
let fill_color = Color::rgba8(0x00, 0x00, 0x00, 0x7F);
paint_ctx.fill(rect, &fill_color);
let font = paint_ctx
.text()
.new_font_by_name("Segoe UI", 24.0)
.build()
.unwrap();
let layout = paint_ctx
.text()
.new_text_layout(&font, data)
.build()
.unwrap();
paint_ctx
.with_save(|rc| {
rc.transform(Affine::rotate(0.1));
rc.draw_text(&layout, (80.0, 40.0), &fill_color);
Ok(())
})
.unwrap();
let image_data = make_image_data(256, 256);
let image = paint_ctx
.make_image(256, 256, &image_data, ImageFormat::RgbaSeparate)
.unwrap();
paint_ctx.draw_image(
&image,
Rect::from_origin_size(Point::ORIGIN, size),
InterpolationMode::Bilinear,
);
}
}
fn main() {
let window = WindowDesc::new(|| CustomWidget {});
AppLauncher::with_window(window)
.use_simple_logger()
.launch("Druid + Piet".to_string())
.expect("launch failed");
}
fn make_image_data(width: usize, height: usize) -> Vec<u8> {
let mut result = vec![0; width * height * 4];
for y in 0..height {
for x in 0..width {
let ix = (y * width + x) * 4;
result[ix + 0] = x as u8;
result[ix + 1] = y as u8;
result[ix + 2] = !(x as u8);
result[ix + 3] = 127;
}
}
result
}