mirror of
https://github.com/obsqrbtz/egui_knob.git
synced 2026-04-08 20:19:17 +03:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c31936f3b0 | |||
| d20180729a | |||
|
|
353dcd8cc4 | ||
| fa7dd9e181 | |||
| a637ff4bca | |||
| e3a378cc6e | |||
|
|
6decbfdca1 | ||
|
|
9facd0fdfd | ||
|
|
37d0792175 | ||
|
|
969ba9bcb5 | ||
| fb3f9d75dc | |||
| 45ce317879 | |||
| 15021b8cfa | |||
|
|
ad468ae18a | ||
|
|
2c5b209571 | ||
| c1db9a2e5b | |||
| 750d8afb25 | |||
| 4e8975c955 | |||
|
|
824b492b92 | ||
| a70b57e62b | |||
| a2a102cdb6 | |||
| 14a143708f | |||
| 2db5eb3d76 | |||
| aab41e9c0e | |||
| 9486b985f1 | |||
| 3a3c2db4d3 | |||
| 427434c607 | |||
| bcfcb55db3 | |||
| 23b2e3c792 | |||
| c2a1d57a60 | |||
| 05b9eb1df9 | |||
| 86d07f3593 | |||
| 617851102b | |||
| 530ba584bc |
27
.github/workflows/publish.yml
vendored
Normal file
27
.github/workflows/publish.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
name: Publish to crates.io
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Check if version matches tag
|
||||
run: |
|
||||
TAG=${GITHUB_REF#refs/tags/v}
|
||||
CARGO_VERSION=$(grep '^version' Cargo.toml | head -1 | cut -d'"' -f2)
|
||||
if [ "$TAG" != "$CARGO_VERSION" ]; then
|
||||
echo "Tag version ($TAG) doesn't match Cargo.toml version ($CARGO_VERSION)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish to crates.io
|
||||
run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
14
.gitignore
vendored
14
.gitignore
vendored
@@ -1,2 +1,14 @@
|
||||
# Rust
|
||||
/target
|
||||
/examples/target
|
||||
/examples/target
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
81
CHANGELOG.md
81
CHANGELOG.md
@@ -2,11 +2,88 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [Unreleased]
|
||||
## [0.3.11] - 2026-03-30
|
||||
|
||||
- bumped egui version ([#PR10](https://github.com/obsqrbtz/egui_knob/pull/10) by [elwerene](https://github.com/elwerene)
|
||||
|
||||
### 🛠 Maintenance
|
||||
|
||||
## [0.3.10] - 2026-01-23
|
||||
|
||||
### 🚀 Features
|
||||
|
||||
- Add configurable sweep range with `with_sweep_range()` method
|
||||
- added support for logarithmic scaling ([#PR9](https://github.com/obsqrbtz/egui_knob/pull/9) by [bratorange](https://github.com/bratorange))
|
||||
|
||||
## [0.3.9] - 2026-01-13
|
||||
|
||||
### 🚀 Features
|
||||
|
||||
- added support for using mouse scroll wheel to change values ([#PR7](https://github.com/obsqrbtz/egui_knob/pull/7) by [maor1993](https://github.com/maor1993))
|
||||
|
||||
## [0.3.8] - 2026-01-12
|
||||
|
||||
### 🚀 Features
|
||||
|
||||
- added `with_double_click_reset` option ([#PR6](https://github.com/obsqrbtz/egui_knob/pull/6) by [maor1993](https://github.com/maor1993))
|
||||
|
||||
## [0.3.7] - 2026-01-06
|
||||
|
||||
### 🛠 Maintenance
|
||||
|
||||
- expose egui types
|
||||
|
||||
## [0.3.6] - 2025-07-15
|
||||
|
||||
### 🛠 Maintenance
|
||||
|
||||
- cleaned up io a bit
|
||||
|
||||
## [0.3.5] - 2025-07-15
|
||||
|
||||
### 🛠 Maintenance
|
||||
|
||||
- Restructured the project
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- Updated readme, added contributing guidelines
|
||||
|
||||
## [0.3.4] - 2025-07-15
|
||||
|
||||
### 🛠 Maintenance
|
||||
|
||||
- Bump egui version to 0.33
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- Updated usage example in readme
|
||||
|
||||
|
||||
## [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
|
||||
|
||||
|
||||
48
CONTRIBUTING.md
Normal file
48
CONTRIBUTING.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Contributing to egui_knob
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Fork the repository
|
||||
2. Clone your fork: `git clone https://github.com/YOUR_USERNAME/egui_knob.git`
|
||||
3. Create a new branch: `git checkout -b feature/your-feature-name`
|
||||
4. Make your changes
|
||||
5. Test your changes
|
||||
6. Commit your changes
|
||||
7. Push to the branch: `git push origin feature/your-feature-name`
|
||||
8. Submit a pull request
|
||||
|
||||
## Development
|
||||
|
||||
### Building
|
||||
|
||||
```bash
|
||||
cargo build
|
||||
```
|
||||
|
||||
## Running demo app
|
||||
|
||||
```bash
|
||||
cargo run --example example_knob
|
||||
```
|
||||
|
||||
## Code Style
|
||||
|
||||
- Follow Rust standard formatting (use `cargo fmt`)
|
||||
- Write clear, descriptive commit messages
|
||||
- Add documentation for public APIs
|
||||
- Keep changes focused and atomic
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
- Add examples for new features
|
||||
- Keep PRs focused on a single feature or fix
|
||||
- Reference any related issues
|
||||
|
||||
## Reporting Issues
|
||||
|
||||
When reporting issues, please include:
|
||||
- A clear description of the problem
|
||||
- Steps to reproduce
|
||||
- Expected vs actual behavior
|
||||
- Your environment (OS, Rust version)
|
||||
- Minimal code example if applicable
|
||||
2840
Cargo.lock
generated
2840
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
10
Cargo.toml
10
Cargo.toml
@@ -1,10 +1,12 @@
|
||||
[package]
|
||||
name = "egui_knob"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
version = "0.3.11"
|
||||
edition = "2024"
|
||||
authors = ["Daniel Dada"]
|
||||
description = "A simple knob widget for egui"
|
||||
homepage = "https://github.com/obsqrbtz/egui_knob"
|
||||
repository = "https://github.com/obsqrbtz/egui_knob"
|
||||
documentation = "https://docs.rs/egui_knob"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
keywords = ["egui", "ui", "widget", "knob", "range"]
|
||||
@@ -19,7 +21,7 @@ name = "example_knob"
|
||||
path = "examples/example_knob.rs"
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31"
|
||||
egui = "0.34"
|
||||
|
||||
[dev-dependencies]
|
||||
eframe = { version = "0.31.0", features = ["default_fonts"] }
|
||||
eframe = { version = "0.34", features = ["default_fonts"] }
|
||||
|
||||
125
README.md
125
README.md
@@ -1,18 +1,24 @@
|
||||
# egui_knob
|
||||
|
||||

|
||||
[](https://crates.io/crates/egui_knob)
|
||||
[](https://docs.rs/egui_knob)
|
||||
[](LICENSE)
|
||||
|
||||
Simple knob widget for egui.
|
||||
A simple, customizable knob widget for egui.
|
||||
|
||||

|
||||
|
||||
## Features
|
||||
|
||||
- Adjustable size, font size, and stroke width.
|
||||
- Customizable colors for the knob, indicator and text.
|
||||
- Label positions (Top, Bottom, Left, Right).
|
||||
- Label formatting.
|
||||
- Two styles: Wiper and Dot.
|
||||
- Adjustable size, font size, and stroke width
|
||||
- Customizable colors for the knob, indicator, and text
|
||||
- Label positions (Top, Bottom, Left, Right)
|
||||
- Custom label formatting
|
||||
- Two visual styles: Wiper and Dot
|
||||
- Configurable sweep range
|
||||
- Background arc with filled segments
|
||||
- Adjustable drag sensitivity
|
||||
- Logarithmic scaling
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -20,27 +26,100 @@ To use the Knob widget in your project, add the following to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
egui = "0.31"
|
||||
egui_knob = "0.2.0"
|
||||
egui = "0.33"
|
||||
eframe = "0.33"
|
||||
egui_knob = "0.3.11"
|
||||
```
|
||||
|
||||
## Usage example
|
||||
## Usage
|
||||
|
||||
### Basic Example
|
||||
|
||||
```rust
|
||||
use egui::{Color32, Context};
|
||||
use egui_knob::Knob;
|
||||
use egui_knob::{Knob, KnobStyle, LabelPosition};
|
||||
use eframe::egui;
|
||||
|
||||
// ..
|
||||
struct KnobApp {
|
||||
value: f32,
|
||||
}
|
||||
|
||||
let mut value: f32 = 0.5;
|
||||
let knob = Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
|
||||
.with_size(50.0)
|
||||
.with_font_size(14.0)
|
||||
.with_stroke_width(3.0)
|
||||
.with_colors(Color32::GRAY, Color32::WHITE, Color32::WHITE)
|
||||
.with_label("Volume", LabelPosition::Top);
|
||||
impl Default for KnobApp {
|
||||
fn default() -> Self {
|
||||
Self { value: 0.5 }
|
||||
}
|
||||
}
|
||||
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.add(knob);
|
||||
});
|
||||
impl eframe::App for KnobApp {
|
||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
let knob = Knob::new(&mut self.value, 0.0, 1.0, KnobStyle::Wiper)
|
||||
.with_size(50.0)
|
||||
.with_font_size(14.0)
|
||||
.with_colors(egui::Color32::GRAY, egui::Color32::WHITE, egui::Color32::WHITE)
|
||||
.with_stroke_width(3.0)
|
||||
.with_label("Volume", LabelPosition::Top);
|
||||
|
||||
ui.add(knob);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
eframe::run_native(
|
||||
"Knob Example",
|
||||
eframe::NativeOptions::default(),
|
||||
Box::new(|_cc| Ok(Box::new(KnobApp::default()))),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Examples
|
||||
|
||||
#### Custom Sweep Range
|
||||
```rust
|
||||
// 270° sweep starting from the left (9 o'clock position)
|
||||
Knob::new(&mut value, 0.0, 100.0, KnobStyle::Wiper)
|
||||
.with_sweep_range(0.25, 0.75)
|
||||
.with_label("Gain", LabelPosition::Bottom);
|
||||
```
|
||||
|
||||
#### Multi-Turn Knob
|
||||
```rust
|
||||
// 2.5 full rotations
|
||||
Knob::new(&mut value, 0.0, 1.0, KnobStyle::Dot)
|
||||
.with_sweep_range(0.0, 2.5);
|
||||
```
|
||||
|
||||
#### Stepped Values
|
||||
```rust
|
||||
// Snap to 0.1 increments
|
||||
Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
|
||||
.with_step(Some(0.1))
|
||||
.with_label_format(|v| format!("{:.1}", v));
|
||||
```
|
||||
|
||||
#### Custom Formatting
|
||||
```rust
|
||||
// Display as percentage
|
||||
Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
|
||||
.with_label_format(|v| format!("{:.0}%", v * 100.0));
|
||||
```
|
||||
|
||||
#### Logarithmic Knobs
|
||||
```rust
|
||||
// Enable logarithmic scaling
|
||||
Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
|
||||
.with_logarithmic_scaling();
|
||||
```
|
||||
|
||||
## Running demo app
|
||||
|
||||
```bash
|
||||
cargo run --example example_knob
|
||||
```
|
||||
|
||||
Demo app is available at [examples/example_knob.rs](examples/example_knob.rs).
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome. Feel free to open an issue or submit a PR.
|
||||
|
||||
@@ -1,138 +1,128 @@
|
||||
use eframe::egui;
|
||||
use egui_knob::Knob;
|
||||
use egui_knob::{Knob, KnobStyle, LabelPosition};
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_inner_size([600.0, 350.0])
|
||||
.with_title("Knob demo"),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
eframe::run_native(
|
||||
"Knob Example",
|
||||
eframe::NativeOptions::default(),
|
||||
Box::new(|_cc| Ok(Box::new(KnobExample::default()))),
|
||||
"Knob demo",
|
||||
options,
|
||||
Box::new(|_cc| Ok(Box::new(KnobDemo::default()))),
|
||||
)
|
||||
}
|
||||
|
||||
struct KnobExample {
|
||||
basic_value: f32,
|
||||
purple_value: f32,
|
||||
large_value: f32,
|
||||
thick_value: f32,
|
||||
red_value: f32,
|
||||
green_value: f32,
|
||||
blue_value: f32,
|
||||
struct KnobDemo {
|
||||
values: [f32; 6],
|
||||
show_bg_arc: bool,
|
||||
show_filled: bool,
|
||||
use_step: bool,
|
||||
logarithmic_scaling: bool,
|
||||
knob_color: egui::Color32,
|
||||
line_color: egui::Color32,
|
||||
text_color: egui::Color32,
|
||||
}
|
||||
|
||||
impl Default for KnobExample {
|
||||
impl Default for KnobDemo {
|
||||
fn default() -> Self {
|
||||
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,
|
||||
values: [f32::NAN; 6],
|
||||
show_bg_arc: true,
|
||||
show_filled: true,
|
||||
use_step: false,
|
||||
logarithmic_scaling: false,
|
||||
knob_color: egui::Color32::DARK_GRAY,
|
||||
line_color: egui::Color32::LIGHT_BLUE,
|
||||
text_color: egui::Color32::WHITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for KnobExample {
|
||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.add(
|
||||
Knob::new(&mut self.basic_value, 0.0, 100.0, egui_knob::KnobStyle::Dot)
|
||||
.with_label("Basic", egui_knob::LabelPosition::Right)
|
||||
.with_size(40.0)
|
||||
.with_font_size(10.0)
|
||||
.with_colors(
|
||||
egui::Color32::from_rgb(60, 60, 60),
|
||||
egui::Color32::from_rgb(150, 150, 150),
|
||||
egui::Color32::from_rgb(200, 200, 200),
|
||||
),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
println!("Basic value changed: {}", self.basic_value);
|
||||
}
|
||||
impl eframe::App for KnobDemo {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
ui.heading("Knob demo");
|
||||
ui.separator();
|
||||
|
||||
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),
|
||||
);
|
||||
|
||||
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))
|
||||
.with_sweep_range(1. / 8., 0.75),
|
||||
);
|
||||
|
||||
ui.add(
|
||||
Knob::new(&mut self.blue_value, 0.0, 100., 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_sweep_range(0., 2.),
|
||||
);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Global Settings:");
|
||||
ui.checkbox(&mut self.show_bg_arc, "Background arc");
|
||||
ui.checkbox(&mut self.show_filled, "Filled segment");
|
||||
ui.checkbox(&mut self.use_step, "Step (0.02)");
|
||||
ui.checkbox(&mut self.logarithmic_scaling, "Logarithmic");
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Color Theme:");
|
||||
ui.color_edit_button_srgba(&mut self.knob_color);
|
||||
ui.label("Knob");
|
||||
ui.color_edit_button_srgba(&mut self.line_color);
|
||||
ui.label("Indicator");
|
||||
ui.color_edit_button_srgba(&mut self.text_color);
|
||||
ui.label("Text");
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
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()
|
||||
{
|
||||
ui.vertical(|ui| {
|
||||
let mut knob = Knob::new(&mut self.values[i], 0., 1., *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.02))
|
||||
.with_double_click_reset(0.5)
|
||||
.with_middle_scroll();
|
||||
|
||||
if self.logarithmic_scaling {
|
||||
knob = knob.with_logarithmic_scaling();
|
||||
}
|
||||
|
||||
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(knob);
|
||||
});
|
||||
|
||||
if (i + 1) % 3 == 0 {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(10.0);
|
||||
ui.separator();
|
||||
}
|
||||
}
|
||||
|
||||
BIN
scrot.png
BIN
scrot.png
Binary file not shown.
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 112 KiB |
47
src/config.rs
Normal file
47
src/config.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use crate::style::{KnobColors, KnobStyle, LabelPosition};
|
||||
|
||||
pub struct KnobConfig {
|
||||
pub(crate) size: f32,
|
||||
pub(crate) font_size: f32,
|
||||
pub(crate) stroke_width: f32,
|
||||
pub(crate) colors: KnobColors,
|
||||
pub(crate) label: Option<String>,
|
||||
pub(crate) label_position: LabelPosition,
|
||||
pub(crate) style: KnobStyle,
|
||||
pub(crate) label_offset: f32,
|
||||
pub(crate) label_format: Box<dyn Fn(f32) -> String>,
|
||||
pub(crate) step: Option<f32>,
|
||||
pub(crate) drag_sensitivity: f32,
|
||||
pub(crate) show_background_arc: bool,
|
||||
pub(crate) show_filled_segments: bool,
|
||||
pub(crate) min_angle: f32,
|
||||
pub(crate) max_angle: f32,
|
||||
pub(crate) reset_value: Option<f32>,
|
||||
pub(crate) allow_scroll: bool,
|
||||
pub(crate) logarithmic_scaling: bool,
|
||||
}
|
||||
|
||||
impl KnobConfig {
|
||||
pub fn new(style: KnobStyle) -> Self {
|
||||
Self {
|
||||
size: 40.0,
|
||||
font_size: 12.0,
|
||||
stroke_width: 2.0,
|
||||
colors: KnobColors::default(),
|
||||
label: None,
|
||||
label_position: LabelPosition::Bottom,
|
||||
style,
|
||||
label_offset: 1.0,
|
||||
label_format: Box::new(|v| format!("{:.2}", v)),
|
||||
step: None,
|
||||
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,
|
||||
reset_value: None,
|
||||
allow_scroll:false,
|
||||
logarithmic_scaling: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
339
src/lib.rs
339
src/lib.rs
@@ -1,334 +1,9 @@
|
||||
use core::f32;
|
||||
mod config;
|
||||
mod render;
|
||||
mod style;
|
||||
mod widget;
|
||||
|
||||
use egui::{Align2, Color32, Rect, Response, Sense, Stroke, Ui, Vec2, Widget};
|
||||
pub use egui;
|
||||
|
||||
/// Position of the label relative to the knob
|
||||
pub enum LabelPosition {
|
||||
Top,
|
||||
Bottom,
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Visual style of the knob indicator
|
||||
pub enum KnobStyle {
|
||||
/// A line extending from the center to the edge
|
||||
Wiper,
|
||||
/// A dot on the edge of the knob
|
||||
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> {
|
||||
value: &'a mut f32,
|
||||
min: f32,
|
||||
max: f32,
|
||||
size: f32,
|
||||
font_size: f32,
|
||||
stroke_width: f32,
|
||||
knob_color: Color32,
|
||||
line_color: Color32,
|
||||
text_color: Color32,
|
||||
label: Option<String>,
|
||||
label_position: LabelPosition,
|
||||
style: KnobStyle,
|
||||
label_offset: f32,
|
||||
label_format: Box<dyn Fn(f32) -> String>,
|
||||
step: Option<f32>,
|
||||
|
||||
/// 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> {
|
||||
/// 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 {
|
||||
Self {
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
size: 40.0,
|
||||
font_size: 12.0,
|
||||
stroke_width: 2.0,
|
||||
knob_color: Color32::GRAY,
|
||||
line_color: Color32::GRAY,
|
||||
text_color: Color32::WHITE,
|
||||
label: None,
|
||||
label_position: LabelPosition::Bottom,
|
||||
style,
|
||||
label_offset: 1.0,
|
||||
label_format: Box::new(|v| format!("{:.2}", v)),
|
||||
step: None,
|
||||
|
||||
// Hardcode those two angles to ENSURE backward compatibility
|
||||
min_angle: -std::f32::consts::PI,
|
||||
max_angle: std::f32::consts::PI * 0.5,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
// Invalid input, return unchanged
|
||||
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
|
||||
pub fn with_size(mut self, size: f32) -> Self {
|
||||
self.size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the font size for the label
|
||||
pub fn with_font_size(mut self, size: f32) -> Self {
|
||||
self.font_size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the stroke width for the knob's outline and indicator
|
||||
pub fn with_stroke_width(mut self, width: f32) -> Self {
|
||||
self.stroke_width = width;
|
||||
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(
|
||||
mut self,
|
||||
knob_color: Color32,
|
||||
line_color: Color32,
|
||||
text_color: Color32,
|
||||
) -> Self {
|
||||
self.knob_color = knob_color;
|
||||
self.line_color = line_color;
|
||||
self.text_color = text_color;
|
||||
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 {
|
||||
self.label = Some(label.into());
|
||||
self.label_position = position;
|
||||
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<'_> {
|
||||
fn ui(self, ui: &mut Ui) -> Response {
|
||||
let knob_size = Vec2::splat(self.size);
|
||||
|
||||
let label_size = if let Some(label) = &self.label {
|
||||
let font_id = egui::FontId::proportional(self.font_size);
|
||||
let max_text = format!("{}: {}", label, (self.label_format)(self.max));
|
||||
ui.painter()
|
||||
.layout(max_text, font_id, Color32::WHITE, f32::INFINITY)
|
||||
.size()
|
||||
} else {
|
||||
Vec2::ZERO
|
||||
};
|
||||
|
||||
let label_padding = 2.0;
|
||||
|
||||
let adjusted_size = match self.label_position {
|
||||
LabelPosition::Top | LabelPosition::Bottom => Vec2::new(
|
||||
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 * 2.0 + self.label_offset,
|
||||
knob_size.y.max(label_size.y + label_padding * 2.0),
|
||||
),
|
||||
};
|
||||
|
||||
let (rect, mut response) = ui.allocate_exact_size(adjusted_size, Sense::drag());
|
||||
|
||||
if response.dragged() {
|
||||
let delta = response.drag_delta().y;
|
||||
let range = self.max - self.min;
|
||||
let step = self.step.unwrap_or(range * 0.005);
|
||||
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 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 angle = if self.min == self.max {
|
||||
// If min == max, just return min angle
|
||||
// That's a edge case, using a 0 range knob is pretty useless
|
||||
self.min_angle
|
||||
} else {
|
||||
self.min_angle
|
||||
+ (*self.value - self.min) / (self.max - self.min)
|
||||
* (self.max_angle - self.min_angle)
|
||||
};
|
||||
|
||||
painter.circle_stroke(
|
||||
center,
|
||||
radius,
|
||||
Stroke::new(self.stroke_width, self.knob_color),
|
||||
);
|
||||
|
||||
match self.style {
|
||||
KnobStyle::Wiper => {
|
||||
let pointer = center + Vec2::angled(angle) * (radius * 0.7);
|
||||
painter.line_segment(
|
||||
[center, pointer],
|
||||
Stroke::new(self.stroke_width * 1.5, self.line_color),
|
||||
);
|
||||
}
|
||||
KnobStyle::Dot => {
|
||||
let dot_pos = center + Vec2::angled(angle) * (radius * 0.7);
|
||||
painter.circle_filled(dot_pos, self.stroke_width * 1.5, self.line_color);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(label) = self.label {
|
||||
let label_text = format!("{}: {}", label, (self.label_format)(*self.value));
|
||||
let font_id = egui::FontId::proportional(self.font_size);
|
||||
|
||||
let (label_pos, alignment) = match self.label_position {
|
||||
LabelPosition::Top => (
|
||||
Vec2::new(
|
||||
rect.center().x,
|
||||
rect.min.y - self.label_offset + label_padding,
|
||||
),
|
||||
Align2::CENTER_TOP,
|
||||
),
|
||||
LabelPosition::Bottom => (
|
||||
Vec2::new(rect.center().x, rect.max.y + self.label_offset),
|
||||
Align2::CENTER_BOTTOM,
|
||||
),
|
||||
LabelPosition::Left => (
|
||||
Vec2::new(rect.min.x - self.label_offset, rect.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
),
|
||||
LabelPosition::Right => (
|
||||
Vec2::new(rect.max.x + self.label_offset, rect.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
),
|
||||
};
|
||||
|
||||
ui.painter().text(
|
||||
label_pos.to_pos2(),
|
||||
alignment,
|
||||
label_text,
|
||||
font_id,
|
||||
self.text_color,
|
||||
);
|
||||
}
|
||||
|
||||
// Draw the bounding rect
|
||||
//painter.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::RED));
|
||||
|
||||
response
|
||||
}
|
||||
}
|
||||
pub use style::{KnobStyle, LabelPosition};
|
||||
pub use widget::Knob;
|
||||
|
||||
206
src/render.rs
Normal file
206
src/render.rs
Normal file
@@ -0,0 +1,206 @@
|
||||
use egui::{Align2, Color32, Painter, Pos2, Rect, Stroke, Ui, Vec2};
|
||||
|
||||
use crate::config::KnobConfig;
|
||||
use crate::style::{KnobStyle, LabelPosition};
|
||||
|
||||
pub(crate) struct KnobRenderer<'a> {
|
||||
config: &'a KnobConfig,
|
||||
value: f32,
|
||||
raw: f32,
|
||||
min: f32,
|
||||
max: f32,
|
||||
}
|
||||
|
||||
impl<'a> KnobRenderer<'a> {
|
||||
pub fn new(config: &'a KnobConfig, value: f32, raw: f32, min: f32, max: f32) -> Self {
|
||||
Self {
|
||||
config,
|
||||
value,
|
||||
raw,
|
||||
min,
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compute_angle(&self) -> f32 {
|
||||
if self.min == self.max || self.raw.is_nan() {
|
||||
self.config.min_angle
|
||||
} else {
|
||||
self.config.min_angle
|
||||
+ self.raw * (self.config.max_angle - self.config.min_angle)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_knob(&self, painter: &Painter, center: Pos2, radius: f32, hovered: bool) {
|
||||
let knob_color = if hovered {
|
||||
self.config.colors.knob_color.linear_multiply(1.15)
|
||||
} else {
|
||||
self.config.colors.knob_color
|
||||
};
|
||||
|
||||
// TODO: make an option
|
||||
painter.circle_filled(
|
||||
center,
|
||||
radius - self.config.stroke_width / 2.0,
|
||||
self.config.colors.knob_color.gamma_multiply(0.15),
|
||||
);
|
||||
|
||||
painter.circle_stroke(
|
||||
center,
|
||||
radius,
|
||||
Stroke::new(self.config.stroke_width, knob_color),
|
||||
);
|
||||
|
||||
if self.config.show_background_arc {
|
||||
self.render_background_arc(painter, center, radius);
|
||||
}
|
||||
|
||||
let angle = self.compute_angle();
|
||||
match self.config.style {
|
||||
KnobStyle::Wiper => {
|
||||
let pointer = center + Vec2::angled(angle) * (radius * 0.65);
|
||||
painter.line_segment(
|
||||
[center, pointer],
|
||||
Stroke::new(
|
||||
self.config.stroke_width * 1.2,
|
||||
self.config.colors.line_color,
|
||||
),
|
||||
);
|
||||
}
|
||||
KnobStyle::Dot => {
|
||||
let dot_pos = center + Vec2::angled(angle) * (radius * 0.7);
|
||||
painter.circle_filled(
|
||||
dot_pos,
|
||||
self.config.stroke_width * 1.8,
|
||||
self.config.colors.line_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_background_arc(&self, painter: &Painter, center: Pos2, radius: f32) {
|
||||
let arc_start = self.config.min_angle;
|
||||
let arc_end = self.config.max_angle;
|
||||
let segments = 128;
|
||||
let arc_color = self.config.colors.knob_color.gamma_multiply(0.35);
|
||||
let arc_radius = radius * 0.85;
|
||||
|
||||
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.config.stroke_width, arc_color),
|
||||
));
|
||||
|
||||
if self.config.show_filled_segments {
|
||||
let filled_segments = (segments as f32
|
||||
* self.raw.clamp(0.0, 1.0))
|
||||
as usize;
|
||||
|
||||
if filled_segments > 0 {
|
||||
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.config.stroke_width * 1.2,
|
||||
self.config.colors.line_color,
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_label(&self, ui: &Ui, rect: Rect) {
|
||||
if let Some(label) = &self.config.label {
|
||||
let label_text = format!("{}: {}", label, (self.config.label_format)(self.value));
|
||||
let font_id = egui::FontId::proportional(self.config.font_size);
|
||||
let label_padding = 4.0;
|
||||
|
||||
let (label_pos, alignment) = match self.config.label_position {
|
||||
LabelPosition::Top => (
|
||||
Vec2::new(rect.center().x, rect.min.y + label_padding),
|
||||
Align2::CENTER_TOP,
|
||||
),
|
||||
LabelPosition::Bottom => (
|
||||
Vec2::new(rect.center().x, rect.max.y - label_padding),
|
||||
Align2::CENTER_BOTTOM,
|
||||
),
|
||||
LabelPosition::Left => (
|
||||
Vec2::new(rect.min.x + label_padding, rect.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
),
|
||||
LabelPosition::Right => (
|
||||
Vec2::new(rect.max.x - label_padding, rect.center().y),
|
||||
Align2::RIGHT_CENTER,
|
||||
),
|
||||
};
|
||||
|
||||
ui.painter().text(
|
||||
label_pos.to_pos2(),
|
||||
alignment,
|
||||
label_text,
|
||||
font_id,
|
||||
self.config.colors.text_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calculate_size(&self, ui: &Ui) -> Vec2 {
|
||||
let knob_size = Vec2::splat(self.config.size + self.config.stroke_width * 2.0);
|
||||
|
||||
let label_size = if let Some(label) = &self.config.label {
|
||||
let font_id = egui::FontId::proportional(self.config.font_size);
|
||||
let max_text = format!("{}: {}", label, (self.config.label_format)(self.max));
|
||||
ui.painter()
|
||||
.layout(max_text, font_id, Color32::WHITE, f32::INFINITY)
|
||||
.size()
|
||||
} else {
|
||||
Vec2::ZERO
|
||||
};
|
||||
|
||||
let label_padding = 8.0;
|
||||
|
||||
match self.config.label_position {
|
||||
LabelPosition::Top | LabelPosition::Bottom => Vec2::new(
|
||||
knob_size.x.max(label_size.x + label_padding * 2.0),
|
||||
knob_size.y + label_size.y + label_padding + self.config.label_offset,
|
||||
),
|
||||
LabelPosition::Left | LabelPosition::Right => Vec2::new(
|
||||
knob_size.x + label_size.x + label_padding + self.config.label_offset,
|
||||
knob_size.y.max(label_size.y + label_padding),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calculate_knob_rect(&self, rect: Rect) -> Rect {
|
||||
let knob_size = Vec2::splat(self.config.size);
|
||||
|
||||
match self.config.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,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
44
src/style.rs
Normal file
44
src/style.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use egui::Color32;
|
||||
|
||||
/// Visual style of the knob indicator
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum KnobStyle {
|
||||
/// A line extending from the center to the edge
|
||||
Wiper,
|
||||
/// A dot on the edge of the knob
|
||||
Dot,
|
||||
}
|
||||
|
||||
/// Position of the label relative to the knob
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LabelPosition {
|
||||
/// Label appears above the knob
|
||||
Top,
|
||||
/// Label appears below the knob
|
||||
Bottom,
|
||||
/// Label appears to the left of the knob
|
||||
Left,
|
||||
/// Label appears to the right of the knob
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Color configuration for the knob widget
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct KnobColors {
|
||||
/// Color of the knob's outline
|
||||
pub knob_color: Color32,
|
||||
/// Color of the indicator (wiper or dot)
|
||||
pub line_color: Color32,
|
||||
/// Color of the label text
|
||||
pub text_color: Color32,
|
||||
}
|
||||
|
||||
impl Default for KnobColors {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
knob_color: Color32::GRAY,
|
||||
line_color: Color32::GRAY,
|
||||
text_color: Color32::WHITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
250
src/widget.rs
Normal file
250
src/widget.rs
Normal file
@@ -0,0 +1,250 @@
|
||||
use egui::{remap, Color32, Response, Sense, Ui, Widget};
|
||||
|
||||
use crate::config::KnobConfig;
|
||||
use crate::render::KnobRenderer;
|
||||
use crate::style::{KnobStyle, LabelPosition};
|
||||
|
||||
pub struct Knob<'a> {
|
||||
pub(crate) value: &'a mut f32,
|
||||
pub(crate) min: f32,
|
||||
pub(crate) max: f32,
|
||||
pub(crate) config: KnobConfig,
|
||||
}
|
||||
|
||||
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 {
|
||||
Self {
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
config: KnobConfig::new(style),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.config.min_angle =
|
||||
start_angle_normalized.rem_euclid(1.0) * std::f32::consts::TAU + std::f32::consts::PI / 2.0;
|
||||
self.config.max_angle = self.config.min_angle + range.max(0.0) * std::f32::consts::TAU;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the size of the knob
|
||||
pub fn with_size(mut self, size: f32) -> Self {
|
||||
self.config.size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the font size for the label
|
||||
pub fn with_font_size(mut self, size: f32) -> Self {
|
||||
self.config.font_size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the stroke width for the knob's outline and indicator
|
||||
pub fn with_stroke_width(mut self, width: f32) -> Self {
|
||||
self.config.stroke_width = width;
|
||||
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(
|
||||
mut self,
|
||||
knob_color: Color32,
|
||||
line_color: Color32,
|
||||
text_color: Color32,
|
||||
) -> Self {
|
||||
self.config.colors.knob_color = knob_color;
|
||||
self.config.colors.line_color = line_color;
|
||||
self.config.colors.text_color = text_color;
|
||||
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 {
|
||||
self.config.label = Some(label.into());
|
||||
self.config.label_position = position;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the spacing between the knob and its label
|
||||
pub fn with_label_offset(mut self, offset: f32) -> Self {
|
||||
self.config.label_offset = offset;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a custom format function for displaying the value
|
||||
///
|
||||
/// # Example
|
||||
/// ```no_run
|
||||
/// use egui_knob::{Knob, KnobStyle};
|
||||
/// ui.add(
|
||||
/// 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.config.label_format = Box::new(format);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the step size for value changes
|
||||
pub fn with_step(mut self, step: Option<f32>) -> Self {
|
||||
self.config.step = step;
|
||||
self
|
||||
}
|
||||
|
||||
/// Controls whether to show the background arc indicating the full range
|
||||
pub fn with_background_arc(mut self, enabled: bool) -> Self {
|
||||
self.config.show_background_arc = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Controls whether to show the filled segment on the background arc
|
||||
///
|
||||
/// When enabled (and background arc is visible), displays a colored segment
|
||||
/// from the minimum position to the current value position.
|
||||
pub fn with_show_filled_segments(mut self, enabled: bool) -> Self {
|
||||
self.config.show_filled_segments = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the drag sensitivity for mouse interactions
|
||||
///
|
||||
/// Default is 0.005.
|
||||
pub fn with_drag_sensitivity(mut self, sensitivity: f32) -> Self {
|
||||
self.config.drag_sensitivity = sensitivity;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a reset value to return to on doubleclick event.
|
||||
pub fn with_double_click_reset(mut self, reset_value: f32) -> Self {
|
||||
self.config.reset_value = Some(reset_value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Allows user to use scroll wheel to change knob value
|
||||
/// Uses config.step for the increment value
|
||||
pub fn with_middle_scroll(mut self) -> Self {
|
||||
self.config.allow_scroll = true;
|
||||
self
|
||||
}
|
||||
pub fn with_logarithmic_scaling(mut self) -> Self {
|
||||
self.config.logarithmic_scaling = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for Knob<'_> {
|
||||
fn ui(self, ui: &mut Ui) -> Response {
|
||||
if self.value.is_nan() {
|
||||
*self.value = self.min;
|
||||
}
|
||||
|
||||
let mut raw = if self.config.logarithmic_scaling {
|
||||
remap(*self.value, self.min..=self.max, 1.0..=10.0).log(10.0)
|
||||
} else {
|
||||
remap(*self.value, self.min..=self.max, 0.0..=1.0)
|
||||
};
|
||||
|
||||
let renderer = KnobRenderer::new(&self.config, *self.value, raw, self.min, self.max);
|
||||
let adjusted_size = renderer.calculate_size(ui);
|
||||
|
||||
let (rect, response) = ui.allocate_exact_size(adjusted_size, Sense::click_and_drag());
|
||||
|
||||
let mut response = response;
|
||||
if response.dragged() {
|
||||
let delta = response.drag_delta().y;
|
||||
let step = self.config.step.unwrap_or(self.config.drag_sensitivity);
|
||||
raw = (raw - delta * step).clamp(0.0,1.0);
|
||||
|
||||
raw = if let Some(step) = self.config.step {
|
||||
let steps = (raw / step).round();
|
||||
(steps * step).clamp(0.0, 1.0)
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
|
||||
if self.value.is_nan() {
|
||||
*self.value = 0.0;
|
||||
}
|
||||
|
||||
response.mark_changed();
|
||||
} else if response.hovered() & self.config.allow_scroll && let Some(scoll) = ui.input(|input| {
|
||||
input.events.iter().find_map(|e| match e {
|
||||
egui::Event::MouseWheel { delta, .. } => Some(*delta),
|
||||
_ => None,
|
||||
})
|
||||
}) {
|
||||
raw = (raw
|
||||
+ scoll.y * self.config.step.unwrap_or(self.config.drag_sensitivity))
|
||||
.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
*self.value = if self.config.logarithmic_scaling {
|
||||
remap(10f32.powf(raw), 1.0..=10.0, self.min..=self.max)
|
||||
}else {
|
||||
remap(raw, 0.0..=1.0, self.min..=self.max)
|
||||
};
|
||||
|
||||
if response.double_clicked()
|
||||
&& let Some(reset_value) = self.config.reset_value {
|
||||
*self.value = reset_value
|
||||
}
|
||||
|
||||
let knob_rect = renderer.calculate_knob_rect(rect);
|
||||
let center = knob_rect.center();
|
||||
let radius = self.config.size / 2.0;
|
||||
|
||||
let updated_renderer = KnobRenderer::new(&self.config, *self.value, raw, self.min, self.max);
|
||||
updated_renderer.render_knob(ui.painter(), center, radius, response.hovered());
|
||||
updated_renderer.render_label(ui, rect);
|
||||
|
||||
if self.config.label.is_some() && response.hovered() {
|
||||
response
|
||||
.clone()
|
||||
.on_hover_text((self.config.label_format)(*self.value));
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user