Back to Blog

Rust egui Tutorial #19: Custom Painting — Draw Shapes with the Painter API

Sandy LaneSandy Lane

Video: Rust egui Tutorial #19: Custom Painting — Draw Shapes with the Painter API by Taught by Celeste AI - AI Coding Coach

Watch full page →

Rust egui Tutorial #19: Custom Painting — Draw Shapes with the Painter API

In this tutorial, you’ll learn how to draw custom shapes on an egui canvas using the Painter API. We cover drawing lines, circles, rectangles, and triangles with precise control over colors, strokes, and positions to create interactive GUI elements.

Code

use eframe::egui::{self, Color32, Painter, Pos2, Rect, Rgba, Shape, Stroke};

fn custom_painting_example(painter: &Painter, center: Pos2) {
  // Draw a red line segment
  let start = Pos2::new(center.x - 50.0, center.y);
  let end = Pos2::new(center.x + 50.0, center.y);
  painter.line_segment([start, end], Stroke::new(2.0, Color32::RED));

  // Draw a filled blue circle
  painter.circle_filled(center, 30.0, Color32::from_rgb(0, 0, 255));

  // Draw a green stroked circle
  painter.circle_stroke(center, 40.0, Stroke::new(3.0, Color32::from_rgb(0, 255, 0)));

  // Draw a filled yellow rectangle centered at `center`
  let rect = Rect::from_center_size(center, egui::vec2(80.0, 40.0));
  painter.rect_filled(rect, 5.0, Color32::from_rgb(255, 255, 0));

  // Draw a stroked rectangle with rounded corners
  painter.rect_stroke(rect.shrink(5.0), 10.0, Stroke::new(2.0, Color32::from_rgb(200, 100, 0)));

  // Draw a triangle using a convex polygon shape
  let points = [
    Pos2::new(center.x, center.y - 40.0),
    Pos2::new(center.x - 35.0, center.y + 20.0),
    Pos2::new(center.x + 35.0, center.y + 20.0),
  ];
  let triangle = Shape::convex_polygon(points.to_vec(), Color32::from_rgb(150, 0, 150), Stroke::new(2.0, Color32::BLACK));
  painter.add(triangle);
}

Key Points

  • Use ui.painter() to obtain a Painter for custom drawing on the egui canvas.
  • Draw lines with line_segment using start/end positions and stroke styles.
  • Draw circles and rectangles filled or stroked with precise size and color control.
  • Create complex shapes like triangles with Shape::convex_polygon and add them to the painter.
  • Use Color32::from_rgb or Rgba::from_rgb for accurate color specification in sRGB space.