Back to Blog

Build a Color Palette App with egui Color Picker | Rust GUI Ep 12

Sandy LaneSandy Lane

Video: Build a Color Palette App with egui Color Picker | Rust GUI Ep 12 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Build a Color Palette App with egui Color Picker

Learn how to create an interactive color palette app using Rust's egui library, featuring a color picker, saved swatches, and hex color codes. This example demonstrates how to use egui's color_edit_button_rgb for selecting colors, convert colors correctly between linear and sRGB spaces with Rgba and Color32, and draw custom-sized color swatches with allocate_exact_size and the painter API.

Code

use egui::{Color32, Rgba, Vec2};

fn ui_color_palette(ui: &mut egui::Ui, colors: &mut Vec) {
  ui.vertical(|ui| {
    // Color picker button for the last color in the palette
    if let Some(last_color) = colors.last_mut() {
      ui.color_edit_button_rgb(last_color);
    }

    ui.separator();

    // Display saved color swatches with hex codes
    for color in colors.iter() {
      // Convert linear Rgba to sRGB Color32 for display
      let color32: Color32 = (*color).into();

      // Allocate exact size for the swatch rectangle
      let (rect, _response) = ui.allocate_exact_size(Vec2::splat(30.0), egui::Sense::hover());

      // Draw filled rectangle with the color
      ui.painter().rect_filled(rect, 4.0, color32);

      // Show hex code below the swatch
      let hex_code = format!(
        "#{:02X}{:02X}{:02X}",
        color32.r(),
        color32.g(),
        color32.b()
      );
      ui.label(hex_code);
    }
  });
}

// Example usage in egui app state
struct MyApp {
  colors: Vec,
}

impl MyApp {
  fn ui(&mut self, ctx: &egui::Context) {
    egui::SidePanel::left("palette_panel").show(ctx, |ui| {
      ui_color_palette(ui, &mut self.colors);
    });
  }
}

Key Points

  • color_edit_button_rgb() creates an interactive RGB color picker button in egui.
  • Use Rgba::from_rgb() and convert to Color32 for correct linear-to-sRGB color representation.
  • allocate_exact_size() reserves precise space for custom widget drawing like color swatches.
  • The painter API’s rect_filled() method draws colored rectangles with rounded corners.
  • Format colors as hex strings with {:02X} to display user-friendly color codes.