15 Commits

Author SHA1 Message Date
3a3c2db4d3 bump version 2025-07-16 02:22:57 +03:00
427434c607 updated changelog and fixed readme 2025-07-16 02:22:18 +03:00
bcfcb55db3 updated example 2025-07-16 02:16:00 +03:00
23b2e3c792 fix: handle NaNs, update example 2025-07-16 02:07:48 +03:00
c2a1d57a60 feat: show progress on background arc
feat: display tooltip showing current value
2025-07-16 01:27:48 +03:00
05b9eb1df9 added background arc 2025-07-16 01:17:51 +03:00
86d07f3593 fix: hover highlights 2025-07-16 01:09:38 +03:00
617851102b chore: bump egui version, closes #3 2025-07-15 14:51:29 +03:00
530ba584bc chore: bump version 2025-07-07 16:49:12 +03:00
135d70cfc8 Merge pull request #2 from sacha-renault/feat/configurable-sweep-range
Allow customizable sweep range for knob widgets
2025-07-07 16:34:48 +03:00
sacha-renault
c105722eb4 fix: Address PR feedback
Prevent division by zero when min equals max value

Also improves angle calculations using TAU constant and adds NaN validation.
Also fix doc
2025-07-06 09:36:29 +02:00
sacha-renault
2a68f53a37 docs: update changelog for sweep range feature 2025-07-05 21:52:05 +02:00
sacha-renault
9968afbe48 feat: Add with_sweep_range() method for
control over knob start position and rotation range. Maintains backward compatibility
2025-07-05 21:45:57 +02:00
06bca1c13a Merge pull request #1 from chloebrett/master
chore: bump deps, fix typos.
2025-05-12 08:42:37 +03:00
Chloe Brett
0a2915f31b Bump egui and eframe versions. Therefore bump minor version (as this is a breaking change to the same extent as the egui bump). 2025-04-06 21:48:53 +10:00
7 changed files with 620 additions and 619 deletions

View File

@@ -2,6 +2,32 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## [0.3.1] - 2025-07-15
### 🚀 Features
- Added background arc
### 🐛 Bug Fixes
- Sanitize NaNs
## [0.3.1] - 2025-07-15
### 🛠 Maintenance
- Bump egui version to 0.32
## [0.3.0] - 2025-07-07
### 🚀 Features
- Add configurable sweep range with `with_sweep_range()` method ([PR#2](https://github.com/obsqrbtz/egui_knob/pull/2) by [sacha-renault](https://github.com/sacha-renault))
## [0.2.0] - 2025-05-12
- Bump egui and eframe versions ([PR#1](https://github.com/obsqrbtz/egui_knob/pull/1) by [chloebrett](https://github.com/chloebrett))
## [0.1.9] - 2025-02-04 ## [0.1.9] - 2025-02-04
### 🚀 Features ### 🚀 Features
@@ -21,6 +47,6 @@ All notable changes to this project will be documented in this file.
### 🐛 Bug Fixes ### 🐛 Bug Fixes
- Mark reponse changed when knob was dragged - Mark response changed when knob was dragged
<!-- generated by git-cliff --> <!-- generated by git-cliff -->

837
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
[package] [package]
name = "egui_knob" name = "egui_knob"
version = "0.1.9" version = "0.3.3"
edition = "2021" edition = "2024"
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"
repository = "https://github.com/obsqrbtz/egui_knob" repository = "https://github.com/obsqrbtz/egui_knob"
@@ -19,7 +19,7 @@ name = "example_knob"
path = "examples/example_knob.rs" path = "examples/example_knob.rs"
[dependencies] [dependencies]
egui = "0.30" egui = "0.32"
[dev-dependencies] [dev-dependencies]
eframe = { version = "0.30.0", features = ["default_fonts"] } eframe = { version = "0.32.0", features = ["default_fonts"] }

View File

@@ -11,7 +11,7 @@ Simple knob widget for egui.
- Adjustable size, font size, and stroke width. - Adjustable size, font size, and stroke width.
- Customizable colors for the knob, indicator and text. - Customizable colors for the knob, indicator and text.
- Label positions (Top, Bottom, Left, Right). - Label positions (Top, Bottom, Left, Right).
- Label formating. - Label formatting.
- Two styles: Wiper and Dot. - Two styles: Wiper and Dot.
## Installation ## Installation
@@ -20,8 +20,8 @@ To use the Knob widget in your project, add the following to your `Cargo.toml`:
```toml ```toml
[dependencies] [dependencies]
egui = "0.30" egui = "0.32"
egui_knob = "*" egui_knob = "0.3.3"
``` ```
## Usage example ## Usage example

View File

@@ -1,136 +1,112 @@
use eframe::egui; use eframe::egui;
use egui_knob::Knob; use egui_knob::{Knob, KnobStyle, LabelPosition};
fn main() -> eframe::Result<()> { fn main() -> eframe::Result<()> {
eframe::run_native( eframe::run_native(
"Knob Example", "egui_knob demo",
eframe::NativeOptions::default(), eframe::NativeOptions::default(),
Box::new(|_cc| Ok(Box::new(KnobExample::default()))), Box::new(|_cc| Ok(Box::new(KnobDemo::default()))),
) )
} }
struct KnobExample { struct KnobDemo {
basic_value: f32, values: [f32; 6],
purple_value: f32, show_bg_arc: bool,
large_value: f32, show_filled: bool,
thick_value: f32, use_step: bool,
red_value: f32, knob_color: egui::Color32,
green_value: f32, line_color: egui::Color32,
blue_value: f32, text_color: egui::Color32,
} }
impl Default for KnobExample { impl Default for KnobDemo {
fn default() -> Self { fn default() -> Self {
Self { Self {
basic_value: 0.0, values: [f32::NAN; 6],
purple_value: 0.0, show_bg_arc: true,
large_value: 0.0, show_filled: true,
thick_value: 0.0, use_step: false,
red_value: 0.0, knob_color: egui::Color32::DARK_GRAY,
green_value: 0.0, line_color: egui::Color32::LIGHT_BLUE,
blue_value: 0.0, text_color: egui::Color32::WHITE,
} }
} }
} }
impl eframe::App for KnobExample { impl eframe::App for KnobDemo {
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.heading("🎛 egui-knob example");
ui.separator();
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui ui.checkbox(&mut self.show_bg_arc, "Show background arc");
.add( ui.checkbox(&mut self.show_filled, "Show filled segment");
Knob::new(&mut self.basic_value, 0.0, 100.0, egui_knob::KnobStyle::Dot) ui.checkbox(&mut self.use_step, "Enable step (0.1)");
.with_label("Basic", egui_knob::LabelPosition::Right) });
.with_size(40.0)
.with_font_size(10.0) ui.horizontal(|ui| {
.with_colors( ui.label("Knob Colors:");
egui::Color32::from_rgb(60, 60, 60), ui.color_edit_button_srgba(&mut self.knob_color);
egui::Color32::from_rgb(150, 150, 150), ui.color_edit_button_srgba(&mut self.line_color);
egui::Color32::from_rgb(200, 200, 200), ui.color_edit_button_srgba(&mut self.text_color);
), });
)
.changed() ui.separator();
ui.label("👇 Scroll or drag knobs to interact:");
ui.add_space(10.0);
egui::Grid::new("knob_grid")
.num_columns(3)
.spacing([30.0, 20.0])
.show(ui, |ui| {
for (i, (label, config)) in [
("Basic Dot", KnobStyle::Dot),
("Wiper, Sweep", KnobStyle::Wiper),
("Thick Stroke", KnobStyle::Wiper),
("360° Sweep", KnobStyle::Wiper),
("Multi-Turn", KnobStyle::Dot),
("Large Font", KnobStyle::Wiper),
]
.iter()
.enumerate()
{ {
println!("Basic value changed: {}", self.basic_value); ui.vertical(|ui| {
ui.label(*label);
let mut knob = Knob::new(&mut self.values[i], 0.0, 1.0, *config)
.with_label(*label, LabelPosition::Bottom)
.with_background_arc(self.show_bg_arc)
.with_show_filled_segments(self.show_filled)
.with_colors(self.knob_color, self.line_color, self.text_color)
.with_step(self.use_step.then_some(0.1));
if *label == "Wiper, Sweep" {
knob = knob.with_sweep_range(0.25, 0.75).with_size(50.0);
}
if *label == "Thick Stroke" {
knob = knob.with_stroke_width(4.0).with_size(60.0);
}
if *label == "360° Sweep" {
knob = knob.with_sweep_range(0.5, 1.0);
}
if *label == "Multi-Turn" {
knob = knob.with_sweep_range(0.0, 2.5);
}
if *label == "Large Font" {
knob = knob.with_size(70.0).with_font_size(18.0);
} }
ui.add( ui.add(knob);
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),
);
ui.add(
Knob::new(
&mut self.green_value,
0.0,
100.0,
egui_knob::KnobStyle::Wiper,
)
.with_label("Leftandlongtext", egui_knob::LabelPosition::Left)
.with_colors(
egui::Color32::from_rgb(30, 80, 30),
egui::Color32::from_rgb(50, 220, 50),
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),
);
}); });
if (i + 1) % 3 == 0 {
ui.end_row();
}
}
});
ui.add_space(10.0);
ui.separator();
}); });
} }
} }

BIN
scrot.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 46 KiB

View File

@@ -1,3 +1,5 @@
use core::f32;
use egui::{Align2, Color32, Rect, 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 /// Position of the label relative to the knob
@@ -9,6 +11,7 @@ pub enum LabelPosition {
} }
/// Visual style of the knob indicator /// Visual style of the knob indicator
#[derive(Clone, Copy)] // <--- add this!
pub enum KnobStyle { pub enum KnobStyle {
/// A line extending from the center to the edge /// A line extending from the center to the edge
Wiper, Wiper,
@@ -42,6 +45,20 @@ pub struct Knob<'a> {
label_offset: f32, label_offset: f32,
label_format: Box<dyn Fn(f32) -> String>, label_format: Box<dyn Fn(f32) -> String>,
step: Option<f32>, step: Option<f32>,
drag_sensitivity: f32,
show_background_arc: bool,
show_filled_segments: bool,
/// Minimum angle in radians.
/// Specifies the lower bound of the knob's rotation.
/// Expected range: 0.0 to TAU. Values outside this range are allowed if your use case requires it.
min_angle: f32,
/// Maximum angle in radians.
/// Specifies the upper bound of the knob's rotation.
/// Can be any value > `min_angle`
/// range `max_angle` - `min_angle` > TAU is allowed but will induce multi-turn
max_angle: f32,
} }
impl<'a> Knob<'a> { impl<'a> Knob<'a> {
@@ -69,9 +86,49 @@ impl<'a> Knob<'a> {
label_offset: 1.0, label_offset: 1.0,
label_format: Box::new(|v| format!("{:.2}", v)), label_format: Box::new(|v| format!("{:.2}", v)),
step: None, step: None,
// Hardcode those two angles to ENSURE backward compatibility
min_angle: -std::f32::consts::PI,
max_angle: std::f32::consts::PI * 0.5,
drag_sensitivity: 0.005,
show_background_arc: true,
show_filled_segments: true,
} }
} }
/// Sets the angular sweep range of the knob
///
/// This controls where the knob starts and how far it can rotate. By default,
/// knobs start at the left (180°) and sweep 270° clockwise to bottom.
///
/// # Arguments
/// * `start_angle_normalized` - Starting position as fraction of full circle:
/// - `0.0` = bottom (6 o'clock)
/// - `0.25` = left (9 o'clock)
/// - `0.5` = top (12 o'clock)
/// - `0.75` = right (3 o'clock)
/// * `range` - How far the knob can sweep as fraction of full circle:
/// - `0.25` = quarter turn (90°)
/// - `0.5` = half turn (180°)
/// - `0.75` = three-quarter turn (270°)
/// - `1.0` = full turn (360°)
/// - Values > 1.0 create multi-turn knobs
/// - Negative values are clamped to 0.0
///
/// Note: the start angle is offset by PI/2 so that `0.0` is at the bottom (6 o'clock)
pub fn with_sweep_range(mut self, start_angle_normalized: f32, range: f32) -> Self {
if start_angle_normalized.is_nan() || range.is_nan() {
return self;
}
self.min_angle =
start_angle_normalized.rem_euclid(1.) * f32::consts::TAU + f32::consts::PI / 2.;
// A range of 1. represent a full turn
self.max_angle = self.min_angle + range.max(0.) * f32::consts::TAU;
self
}
/// Sets the size of the knob /// 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;
@@ -141,14 +198,38 @@ impl<'a> Knob<'a> {
/// Sets the step size for value changes /// Sets the step size for value changes
/// ///
/// When set, the value will snap to discrete steps as the knob is dragged. /// When set, the value will snap to discrete steps as the knob is dragged.
pub fn with_step(mut self, step: f32) -> Self { pub fn with_step(mut self, step: Option<f32>) -> Self {
self.step = Some(step); self.step = step;
self self
} }
/// Shows the background arc showing full range
pub fn with_background_arc(mut self, enabled: bool) -> Self {
self.show_background_arc = enabled;
self
}
/// Shows filled range on the background arc
pub fn with_show_filled_segments(mut self, enabled: bool) -> Self {
self.show_filled_segments = enabled;
self
}
// Private
fn compute_angle(&self) -> f32 {
if self.min == self.max || self.value.is_nan() {
self.min_angle
} else {
self.min_angle
+ (*self.value - self.min) / (self.max - self.min)
* (self.max_angle - self.min_angle)
}
}
} }
impl Widget for Knob<'_> { impl Widget for Knob<'_> {
fn ui(self, ui: &mut Ui) -> Response { fn ui(self, ui: &mut Ui) -> Response {
if self.value.is_nan() {
*self.value = self.min;
}
let knob_size = Vec2::splat(self.size); let knob_size = Vec2::splat(self.size);
let label_size = if let Some(label) = &self.label { let label_size = if let Some(label) = &self.label {
@@ -179,7 +260,7 @@ impl Widget for Knob<'_> {
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 = self.step.unwrap_or(range * 0.005); let step = self.step.unwrap_or(range * self.drag_sensitivity);
let new_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 { *self.value = if let Some(step) = self.step {
@@ -189,6 +270,10 @@ impl Widget for Knob<'_> {
new_value new_value
}; };
if self.value.is_nan() {
*self.value = self.min;
}
response.mark_changed(); response.mark_changed();
} }
@@ -210,14 +295,57 @@ impl Widget for Knob<'_> {
let center = knob_rect.center(); 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.compute_angle();
- std::f32::consts::PI; let knob_hovered = response.hovered();
let knob_color = if knob_hovered {
self.knob_color.linear_multiply(1.2)
} else {
self.knob_color
};
painter.circle_stroke( painter.circle_stroke(center, radius, Stroke::new(self.stroke_width, knob_color));
center,
radius, // Background arc (indicating full range)
Stroke::new(self.stroke_width, self.knob_color), if self.show_background_arc {
); let arc_start = self.min_angle;
let arc_end = self.max_angle;
let segments = 64;
let arc_color = self.knob_color.gamma_multiply(0.5); // dimmed background arc
let arc_radius = radius * 0.8;
let mut points = Vec::with_capacity(segments + 1);
for i in 0..=segments {
let t = i as f32 / segments as f32;
let angle = arc_start + (arc_end - arc_start) * t;
let pos = center + Vec2::angled(angle) * arc_radius;
points.push(pos);
}
painter.add(egui::Shape::line(
points,
Stroke::new(self.stroke_width, arc_color),
));
// Filled part when background arc is enabled
if self.show_filled_segments {
let filled_segments = (segments as f32
* ((*self.value - self.min) / (self.max - self.min)).clamp(0.0, 1.0))
as usize;
let mut fill_points = Vec::with_capacity(filled_segments + 1);
for i in 0..=filled_segments {
let t = i as f32 / segments as f32;
let angle = arc_start + (arc_end - arc_start) * t;
let pos = center + Vec2::angled(angle) * arc_radius;
fill_points.push(pos);
}
painter.add(egui::Shape::line(
fill_points,
Stroke::new(self.stroke_width, self.line_color),
));
}
}
match self.style { match self.style {
KnobStyle::Wiper => { KnobStyle::Wiper => {
@@ -237,6 +365,8 @@ impl Widget for Knob<'_> {
let label_text = format!("{}: {}", label, (self.label_format)(*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 label_padding = 2.0;
let (label_pos, alignment) = match self.label_position { let (label_pos, alignment) = match self.label_position {
LabelPosition::Top => ( LabelPosition::Top => (
Vec2::new( Vec2::new(
@@ -266,6 +396,12 @@ impl Widget for Knob<'_> {
font_id, font_id,
self.text_color, self.text_color,
); );
if response.hovered() {
response
.clone()
.on_hover_text((self.label_format)(*self.value));
}
} }
// Draw the bounding rect // Draw the bounding rect