13 Commits

7 changed files with 285 additions and 69 deletions

26
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,26 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug example 'example_knob'",
"cargo": {
"args": [
"build",
"--example=example_knob",
"--package=egui_knob"
],
"filter": {
"name": "example_knob",
"kind": "example"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
]
}

26
CHANGELOG.md Normal file
View File

@@ -0,0 +1,26 @@
# Changelog
All notable changes to this project will be documented in this file.
## [0.1.9] - 2025-02-04
### 🚀 Features
- Exposed label format
- Add step size configuration
### 🐛 Bug Fixes
- Add label offsets and position in relative to the widget rect
### 📚 Documentation
- Added doc comments
## [0.1.8] - 2025-02-03
### 🐛 Bug Fixes
- Mark reponse changed when knob was dragged
<!-- generated by git-cliff -->

2
Cargo.lock generated
View File

@@ -896,7 +896,7 @@ dependencies = [
[[package]] [[package]]
name = "egui_knob" name = "egui_knob"
version = "0.1.4" version = "0.1.9"
dependencies = [ dependencies = [
"eframe", "eframe",
"egui", "egui",

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "egui_knob" name = "egui_knob"
version = "0.1.4" version = "0.1.9"
edition = "2021" edition = "2021"
description = "A simple knob widget for egui" description = "A simple knob widget for egui"
homepage = "https://github.com/obsqrbtz/egui_knob" homepage = "https://github.com/obsqrbtz/egui_knob"

View File

@@ -9,8 +9,9 @@ Simple knob widget for egui.
## Features ## Features
- Adjustable size, font size, and stroke width. - Adjustable size, font size, and stroke width.
- Customizable colors for the knob and line. - Customizable colors for the knob, indicator and text.
- Label positions (Top, Bottom, Left, Right). - Label positions (Top, Bottom, Left, Right).
- Label formating.
- Two styles: Wiper and Dot. - Two styles: Wiper and Dot.
## Installation ## Installation

View File

@@ -10,12 +10,26 @@ fn main() -> eframe::Result<()> {
} }
struct KnobExample { struct KnobExample {
value: f32, basic_value: f32,
purple_value: f32,
large_value: f32,
thick_value: f32,
red_value: f32,
green_value: f32,
blue_value: f32,
} }
impl Default for KnobExample { impl Default for KnobExample {
fn default() -> Self { fn default() -> Self {
Self { value: 0.0 } Self {
basic_value: 0.0,
purple_value: 0.0,
large_value: 0.0,
thick_value: 0.0,
red_value: 0.0,
green_value: 0.0,
blue_value: 0.0,
}
} }
} }
@@ -23,35 +37,96 @@ impl eframe::App for KnobExample {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| { egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add( if ui
Knob::new(&mut self.value, 0.0, 100.0, egui_knob::KnobStyle::Dot) .add(
.with_label("Gain", egui_knob::LabelPosition::Bottom) Knob::new(&mut self.basic_value, 0.0, 100.0, egui_knob::KnobStyle::Dot)
.with_size(50.0), .with_label("Basic", egui_knob::LabelPosition::Right)
); .with_size(40.0)
ui.add( .with_font_size(10.0)
Knob::new(&mut self.value, 0.0, 100.0, egui_knob::KnobStyle::Wiper)
.with_label("Gain", egui_knob::LabelPosition::Bottom)
.with_size(50.0),
);
ui.add_space(15.0);
ui.add(
Knob::new(&mut self.value, 0.0, 100.0, egui_knob::KnobStyle::Dot)
.with_label("Gain", egui_knob::LabelPosition::Bottom)
.with_colors( .with_colors(
egui::Color32::DARK_GRAY, egui::Color32::from_rgb(60, 60, 60),
egui::Color32::WHITE, egui::Color32::from_rgb(150, 150, 150),
egui::Color32::WHITE, egui::Color32::from_rgb(200, 200, 200),
),
)
.changed()
{
println!("Basic value changed: {}", self.basic_value);
}
ui.add(
Knob::new(
&mut self.purple_value,
0.0,
100.0,
egui_knob::KnobStyle::Wiper,
)
.with_label("Purple", egui_knob::LabelPosition::Bottom)
.with_colors(
egui::Color32::from_rgb(60, 30, 80),
egui::Color32::from_rgb(200, 100, 255),
egui::Color32::from_rgb(230, 150, 255),
)
.with_size(50.0)
.with_font_size(14.0)
.with_stroke_width(3.0)
.with_step(0.1),
);
ui.add(
Knob::new(&mut self.large_value, 0.0, 100.0, egui_knob::KnobStyle::Dot)
.with_label("Large", egui_knob::LabelPosition::Bottom)
.with_size(60.0)
.with_font_size(16.0),
);
ui.add(
Knob::new(
&mut self.thick_value,
0.0,
100.0,
egui_knob::KnobStyle::Wiper,
)
.with_label("Thick", egui_knob::LabelPosition::Bottom)
.with_size(50.0)
.with_stroke_width(4.0),
);
ui.add(
Knob::new(&mut self.red_value, 0.0, 100.0, egui_knob::KnobStyle::Dot)
.with_label("Red", egui_knob::LabelPosition::Bottom)
.with_colors(
egui::Color32::from_rgb(80, 30, 30),
egui::Color32::from_rgb(220, 50, 50),
egui::Color32::from_rgb(255, 100, 100),
) )
.with_size(50.0), .with_size(50.0),
); );
ui.add_space(15.0);
ui.add( ui.add(
Knob::new(&mut self.value, 0.0, 100.0, egui_knob::KnobStyle::Wiper) Knob::new(
.with_label("Gain", egui_knob::LabelPosition::Bottom) &mut self.green_value,
0.0,
100.0,
egui_knob::KnobStyle::Wiper,
)
.with_label("Leftandlongtext", egui_knob::LabelPosition::Left)
.with_colors( .with_colors(
egui::Color32::DARK_GRAY, egui::Color32::from_rgb(30, 80, 30),
egui::Color32::WHITE, egui::Color32::from_rgb(50, 220, 50),
egui::Color32::LIGHT_BLUE, egui::Color32::from_rgb(100, 255, 100),
)
.with_size(50.0)
.with_label_format(|v| format!("{:.2}%", v)),
);
ui.add(
Knob::new(&mut self.blue_value, 0.0, 100.0, egui_knob::KnobStyle::Dot)
.with_label("Top", egui_knob::LabelPosition::Top)
.with_colors(
egui::Color32::from_rgb(30, 30, 80),
egui::Color32::from_rgb(50, 50, 220),
egui::Color32::from_rgb(100, 100, 255),
) )
.with_size(50.0), .with_size(50.0),
); );

View File

@@ -1,5 +1,6 @@
use egui::{Align2, Color32, Response, Sense, Stroke, Ui, Vec2, Widget}; use egui::{Align2, Color32, Rect, Response, Sense, Stroke, Ui, Vec2, Widget};
/// Position of the label relative to the knob
pub enum LabelPosition { pub enum LabelPosition {
Top, Top,
Bottom, Bottom,
@@ -7,11 +8,24 @@ pub enum LabelPosition {
Right, Right,
} }
/// Visual style of the knob indicator
pub enum KnobStyle { pub enum KnobStyle {
/// A line extending from the center to the edge
Wiper, Wiper,
/// A dot on the edge of the knob
Dot, Dot,
} }
/// A circular knob widget for egui that can be dragged to change a value
///
/// # Example
/// ```
/// let mut value = 0.5;
/// Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
/// .with_size(50.0)
/// .with_label("Volume", LabelPosition::Bottom)
/// .with_step(0.1);
/// ```
pub struct Knob<'a> { pub struct Knob<'a> {
value: &'a mut f32, value: &'a mut f32,
min: f32, min: f32,
@@ -25,9 +39,19 @@ pub struct Knob<'a> {
label: Option<String>, label: Option<String>,
label_position: LabelPosition, label_position: LabelPosition,
style: KnobStyle, style: KnobStyle,
label_offset: f32,
label_format: Box<dyn Fn(f32) -> String>,
step: Option<f32>,
} }
impl<'a> Knob<'a> { impl<'a> Knob<'a> {
/// Creates a new knob widget
///
/// # Arguments
/// * `value` - Mutable reference to the value controlled by the knob
/// * `min` - Minimum value
/// * `max` - Maximum value
/// * `style` - Visual style of the knob indicator
pub fn new(value: &'a mut f32, min: f32, max: f32, style: KnobStyle) -> Self { pub fn new(value: &'a mut f32, min: f32, max: f32, style: KnobStyle) -> Self {
Self { Self {
value, value,
@@ -42,24 +66,36 @@ impl<'a> Knob<'a> {
label: None, label: None,
label_position: LabelPosition::Bottom, label_position: LabelPosition::Bottom,
style, style,
label_offset: 1.0,
label_format: Box::new(|v| format!("{:.2}", v)),
step: None,
} }
} }
/// Sets the size of the knob
pub fn with_size(mut self, size: f32) -> Self { pub fn with_size(mut self, size: f32) -> Self {
self.size = size; self.size = size;
self self
} }
/// Sets the font size for the label
pub fn with_font_size(mut self, size: f32) -> Self { pub fn with_font_size(mut self, size: f32) -> Self {
self.font_size = size; self.font_size = size;
self self
} }
/// Sets the stroke width for the knob's outline and indicator
pub fn with_stroke_width(mut self, width: f32) -> Self { pub fn with_stroke_width(mut self, width: f32) -> Self {
self.stroke_width = width; self.stroke_width = width;
self self
} }
/// Sets the colors for different parts of the knob
///
/// # Arguments
/// * `knob_color` - Color of the knob's outline
/// * `line_color` - Color of the indicator
/// * `text_color` - Color of the label text
pub fn with_colors( pub fn with_colors(
mut self, mut self,
knob_color: Color32, knob_color: Color32,
@@ -72,11 +108,43 @@ impl<'a> Knob<'a> {
self self
} }
/// Adds a label to the knob
///
/// # Arguments
/// * `label` - Text to display
/// * `position` - Position of the label relative to the knob
pub fn with_label(mut self, label: impl Into<String>, position: LabelPosition) -> Self { pub fn with_label(mut self, label: impl Into<String>, position: LabelPosition) -> Self {
self.label = Some(label.into()); self.label = Some(label.into());
self.label_position = position; self.label_position = position;
self self
} }
/// Sets the spacing between the knob and its label
pub fn with_label_offset(mut self, offset: f32) -> Self {
self.label_offset = offset;
self
}
/// Sets a custom format function for displaying the value
///
/// # Example
/// ```
/// # let mut value = 0.5;
/// Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
/// .with_label_format(|v| format!("{:.1}%", v * 100.0));
/// ```
pub fn with_label_format(mut self, format: impl Fn(f32) -> String + 'static) -> Self {
self.label_format = Box::new(format);
self
}
/// Sets the step size for value changes
///
/// When set, the value will snap to discrete steps as the knob is dragged.
pub fn with_step(mut self, step: f32) -> Self {
self.step = Some(step);
self
}
} }
impl Widget for Knob<'_> { impl Widget for Knob<'_> {
@@ -85,40 +153,62 @@ impl Widget for Knob<'_> {
let label_size = if let Some(label) = &self.label { let label_size = if let Some(label) = &self.label {
let font_id = egui::FontId::proportional(self.font_size); let font_id = egui::FontId::proportional(self.font_size);
let max_text = format!("{}: {}", label, (self.label_format)(self.max));
ui.painter() ui.painter()
.layout( .layout(max_text, font_id, Color32::WHITE, f32::INFINITY)
format!("{}: {:.2}", label, self.value),
font_id,
Color32::WHITE,
f32::INFINITY,
)
.size() .size()
} else { } else {
Vec2::ZERO Vec2::ZERO
}; };
let label_padding = 12.0; let label_padding = 2.0;
let adjusted_size = match self.label_position { let adjusted_size = match self.label_position {
LabelPosition::Top | LabelPosition::Bottom => { LabelPosition::Top | LabelPosition::Bottom => Vec2::new(
Vec2::new(knob_size.x, knob_size.y + label_size.y + label_padding) knob_size.x.max(label_size.x + label_padding * 2.0),
} knob_size.y + label_size.y + label_padding * 2.0 + self.label_offset,
LabelPosition::Left | LabelPosition::Right => { ),
Vec2::new(knob_size.x + label_size.x + label_padding, knob_size.y) LabelPosition::Left | LabelPosition::Right => Vec2::new(
} knob_size.x + label_size.x + label_padding * 2.0 + self.label_offset,
knob_size.y.max(label_size.y + label_padding * 2.0),
),
}; };
let (rect, response) = ui.allocate_exact_size(adjusted_size, Sense::drag()); let (rect, mut response) = ui.allocate_exact_size(adjusted_size, Sense::drag());
if response.dragged() { if response.dragged() {
let delta = response.drag_delta().y; let delta = response.drag_delta().y;
let range = self.max - self.min; let range = self.max - self.min;
let step = range * 0.005; let step = self.step.unwrap_or(range * 0.005);
*self.value = (*self.value - delta * step).clamp(self.min, self.max); let new_value = (*self.value - delta * step).clamp(self.min, self.max);
*self.value = if let Some(step) = self.step {
let steps = ((new_value - self.min) / step).round();
(self.min + steps * step).clamp(self.min, self.max)
} else {
new_value
};
response.mark_changed();
} }
let painter = ui.painter(); let painter = ui.painter();
let center = rect.center(); let knob_rect = match self.label_position {
LabelPosition::Left => {
Rect::from_min_size(rect.right_top() + Vec2::new(-knob_size.x, 0.0), knob_size)
}
LabelPosition::Right => Rect::from_min_size(rect.left_top(), knob_size),
LabelPosition::Top => Rect::from_min_size(
rect.left_bottom() + Vec2::new((rect.width() - knob_size.x) / 2.0, -knob_size.y),
knob_size,
),
LabelPosition::Bottom => Rect::from_min_size(
rect.left_top() + Vec2::new((rect.width() - knob_size.x) / 2.0, 0.0),
knob_size,
),
};
let center = knob_rect.center();
let radius = knob_size.x / 2.0; let radius = knob_size.x / 2.0;
let angle = (*self.value - self.min) / (self.max - self.min) * std::f32::consts::PI * 1.5 let angle = (*self.value - self.min) / (self.max - self.min) * std::f32::consts::PI * 1.5
- std::f32::consts::PI; - std::f32::consts::PI;
@@ -144,45 +234,43 @@ impl Widget for Knob<'_> {
} }
if let Some(label) = self.label { if let Some(label) = self.label {
let label_text = format!("{label}: {:.2}", self.value); let label_text = format!("{}: {}", label, (self.label_format)(*self.value));
let font_id = egui::FontId::proportional(self.font_size); let font_id = egui::FontId::proportional(self.font_size);
let text_size = ui
.painter()
.layout(
label_text.clone(),
font_id.clone(),
Color32::WHITE,
f32::INFINITY,
)
.size();
let label_offset = label_padding; let (label_pos, alignment) = match self.label_position {
let label_pos = match self.label_position { LabelPosition::Top => (
LabelPosition::Top => { Vec2::new(
rect.center() rect.center().x,
+ Vec2::new(-text_size.x / 2.0, -radius - label_offset - text_size.y) rect.min.y - self.label_offset + label_padding,
} ),
LabelPosition::Bottom => { Align2::CENTER_TOP,
rect.center() + Vec2::new(-text_size.x / 2.0, radius + label_offset) ),
} LabelPosition::Bottom => (
LabelPosition::Left => { Vec2::new(rect.center().x, rect.max.y + self.label_offset),
rect.center() Align2::CENTER_BOTTOM,
+ Vec2::new(-radius - label_offset - text_size.x, -text_size.y / 2.0) ),
} LabelPosition::Left => (
LabelPosition::Right => { Vec2::new(rect.min.x - self.label_offset, rect.center().y),
rect.center() + Vec2::new(radius + label_offset, -text_size.y / 2.0) Align2::LEFT_CENTER,
} ),
LabelPosition::Right => (
Vec2::new(rect.max.x + self.label_offset, rect.center().y),
Align2::RIGHT_CENTER,
),
}; };
ui.painter().text( ui.painter().text(
label_pos, label_pos.to_pos2(),
Align2::LEFT_TOP, alignment,
label_text, label_text,
font_id, font_id,
self.text_color, self.text_color,
); );
} }
// Draw the bounding rect
//painter.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::RED));
response response
} }
} }