ktsu.ImGui.Widgets
3.80.0
Prefix Reserved
See the version list below for details.
dotnet add package ktsu.ImGui.Widgets --version 3.80.0
NuGet\Install-Package ktsu.ImGui.Widgets -Version 3.80.0
<PackageReference Include="ktsu.ImGui.Widgets" Version="3.80.0" />
<PackageVersion Include="ktsu.ImGui.Widgets" Version="3.80.0" />
<PackageReference Include="ktsu.ImGui.Widgets" />
paket add ktsu.ImGui.Widgets --version 3.80.0
#r "nuget: ktsu.ImGui.Widgets, 3.80.0"
#:package ktsu.ImGui.Widgets@3.80.0
#addin nuget:?package=ktsu.ImGui.Widgets&version=3.80.0
#tool nuget:?package=ktsu.ImGui.Widgets&version=3.80.0
ktsu.ImGui.Widgets
ktsu.ImGui.Widgets is a library of custom widgets for Dear ImGui, built on the Hexa.NET.ImGui bindings. It provides a variety of widgets and utilities to enhance your ImGui-based applications.
Features
The widgets below are grouped by what they are for. Everything is a static method on ImGuiWidgets unless it is named as a type.
Input and Controls
Switch: iOS-style toggle with an animated thumb, whose track interpolates between the frame background and the accent colorSegmentedControl: A row of mutually exclusive options with a sliding, animated highlight behind the selected oneStepper: A[-] value [+]integer stepper with hold-to-repeat after a short delayTimecodeField: Edits a frame count shown as SMPTE timecode,HH:MM:SS:FF(;FFfor drop-frame), laid out as[-] value [+]. The buttons step a frame, or a second with Shift; dragging across the value scrubs a frame per pixel (ten with Shift); clicking it opens it for typing, where1:00,2:00:00or bare digits such as10000are read right-aligned; Up and Down step while hovered. The rate is aTimecodeRate, a numerator/denominator pair so 29.97 is exactly 30000/1001, with presets fromFps23_976toFps60including both drop-frame rates. The staticTimecodeclass formats, parses and converts to and from seconds with no ImGui contextValueSlider: A slider for afloatorintdrawn as a frame filled up to the value, with the value written in the middle and no grab over it. Drags are relative, so a press never jumps the value; Shift drags finely, Ctrl+click types a value, and a double-click returns toValueSliderOptions.ResetValue(or types, when there is none).ValueSliderOptionsalso takes a number format, a unit suffix such as%orpx, a prefix such asSizefor a label inside the frame,ValueSliderFill.FromZerofor a bipolar range filled from zero, andLogarithmicfor a size or radius, where each stretch of a drag multiplies the value by the same factor (a range starting at zero keeps zero at its left end and runs logarithmically from the smallest step the format shows). The frame and label are one item, as withImGui.SliderFloat, soIsItemActivatedandIsItemDeactivatedAfterEditwork after it, and the text over the fill switches to a readable color when the theme's own text would not read there. A fill lying wholly under the number, such as a value near zero filled from zero, and the zero mark are drawn only above and below the digits, so nothing runs through themRangeSlider: Dual-handle slider for a span within a range; the handles cannot cross and stay a minimum distance apartChannelFader: Mixing-console gain fader in dB on an audio taper (unity at three quarters of the travel), with a level meter beside the track, a readout underneath, right-click to reset to unity and wheel nudges;FaderTaperexposes the position-to-dB mappingXYPad: Edits two normalized parameters at once from one padColorEdit/ColorPicker/ColorButton: Dear ImGui's colour controls over a colour stored in linear light. What is shown, typed and picked is sRGB-encoded, so mid grey reads #808080; what is written back is linear, and only on an edit, so a colour that is merely displayed stays exactly as stored. Alpha passes through untouched.Vector3andVector4overloadsColorWheel/LiftGammaGain: Colour-grading wheels, singly or as the lift, gamma and gain set a grade is made of. Each is a trackball editing a hue and strength over a master slider for luminance, held in aColorWheelValue. Drags are relative, so a press never jumps the handle; Shift adjusts finely and a double-click resets the ball or the slider.ColorWheelValue.ToRgbOffsetturns a wheel into a per-channel offset, and applying it is left to youKnob/KnobWithDrag: Dial-style knobs in several variants, ported to .NET from ImGui-works/ImGui-knobs-dial-gauge-meterRating: Interactive star rating that previews the value under the cursor before it is committedChip/ChipGroup: Pill-shaped filter or choice tags, filled when selected, and a wrapping single-select group of themPinInput: An N-box PIN or one-time-passcode entry that auto-advances, and steps back on backspaceSearchBox/SearchBoxRanked: Filters a collection withktsu.TextFilter(glob, regex, fuzzy) or ranks it with a fuzzy matchCombo: Type-safe combo boxes for enums, strings, and semantic stringsPianoKeyboard: A horizontal piano keyboard played with the pointer. Returns note-on and note-off as plain MIDI note numbers, with velocity from how far down the key the press lands, slides from key to key while dragging, and highlights notes the caller reports as held.PianoKeyboardLayoutholds the key geometry with no ImGui dependency, so a piano roll can share itStepGrid: A step-sequencer grid of on/off cells, one row per voice and one column per step. A press toggles a cell and a drag paints that cell's new value across a run; the host owns the clock and passes the playing step to highlightTransportScrubber: A video-editor style transport over a caller-ownedTimelineView: time ruler, thumbnail strip from a caller resolver, playhead and in/out range, with frame snapping, I/O and arrow-key shortcuts, and a right-click menu
Display and Status
Avatar: Circular initials avatar on a color derived deterministically from the name, with an optional presence dotBadge/BadgeDot: A count badge (with amaxCount+cap) or a plain dot, overlaid on the corner of the item just submittedColorIndicator: A colored square that shows a stateIcon: Icons with alignment options and click, double-click and context-menu delegatesText: Text with alignment (TextCentered,TextCenteredWithin) and ellipsis clippingImage: Images with alignment (ImageCentered,ImageCenteredWithin), returning whether they were clickedPageIndicator: A row of carousel dots, optionally clickable to jump to a pageTooltip/Breadcrumb: A hover tooltip and a path-style breadcrumb trailDiffView: Draws a diff someone else computed, unified or side by side, with a checkbox per hunk and a proportional summary bar
Progress and Loading
RadialProgressBar: Circular determinate progress, withRadialCountdownandRadialCountUptimer variantsBufferingBar/Spinner: Determinate linear progress, and an indeterminate spinnerSkeletonLine/SkeletonRect/SkeletonCircle: Shimmering placeholders for content that has not loaded, animated fromImGui.GetTime()so they need no per-widget state
Data and Signals
Histogram: One or more binned distributions as overlaid bars, scaled to the tallest bin; it takes pre-computed bins, so the binning scan stays off the render threadFrameTimeGraph: Per-frame times as bars, newest on the right, against a budget line and a line at twice it, with over-budget bars recoloured, a cap on spikes past the scale, a hover tooltip, and a readout of the average, 99th percentile, worst frame and how many went over budget; feed a caller-ownedFrameTimeHistoryonce a frame, or pass any span of millisecondsHandleTrack: Draggable handles over a rectangle you supply — a histogram plot, say — kept ordered and a minimum distance apartFlameGraph: A flame graph over managed sample dataDbMeter: A vertical audio level meter in decibels, with an optional peak-hold markerGainReductionMeter: A vertical meter of how many dB a compressor or limiter is pulling down, filling from the top edge, with an optional held peakCorrelationMeter: A horizontal phase-correlation bar from -1 through 0 to +1, filling outward from the centre; the ballistics live in a caller-ownedStereoMetersStateGoniometer: A Lissajous plot of mid against side for a stereo block, so mono draws a vertical line and inverted material a horizontal oneScope: An oscilloscope-style waveform over a block of audio samplesWaveform: A waveform overview of a whole clip, drawn from a min/max peak overview (ComputeWaveformPeaksbuilds one), with a click-or-drag playhead and a loop region whose edges drag like aHandleTrack's; Shift-drag draws a new loop. A zoomable overload draws the window of a long clip that a caller-ownedTimelineViewshows, from aWaveformPeakSourcesuch as the built-inWaveformPeakCache, a min/max pyramid that keeps a one-sample spike at every zoom; Ctrl+wheel zooms about the pointer, Shift+wheel and the scrollbar scroll, middle-drag pans, a scrub held past an edge scrolls, and the view pages to follow the playheadDataTable: A table of typed rows that sorts and filters itself, moves an active cell with the keyboard, and edits one cell at a time, reporting each edit for you to applySpectrumAnalyzer: Log-frequency bars or a line over FFT magnitudes you supply, with peak hold, coloured inDbMeter's zones; the bands and ballistics live in a caller-ownedSpectrumAnalyzerStateEnvelopeEditor: A DAHDSR envelope drawn from the sameEnvelope.LevelAta synth would call; drag breakpoints to retime segments and set the sustain level, drag tension handles to bend a segment, right-click one to straighten itParametricEq: An EQ response curve with a draggable node per band: drag for frequency and gain, wheel for Q. You plot your own response, orEqResponse's RBJ cookbook biquads;LogFrequencyAxisis shared withSpectrumAnalyzer, so the two line up when stackedLogView: The console panel of an engine or tool: a virtualized log ofLogEntryrows with a text filter, a toggle per level, collapsing of repeated lines, auto-follow that stops when you scroll up and resumes at the bottom, multi-row selection and copy. The log is yours to append to; a caller-ownedLogViewStateindexes it incrementally, so new lines cost only their own filtering
Image and Colour
LevelsControl: A levels control — a histogram with black, grey and white input handles, an output ramp with its own black and white handles, and a numeric readout. It edits a caller-ownedLevelsAdjustment, whoseApplyis the same transfer function the handles describe, so the curve on screen and the curve applied to pixels cannot disagree. Grey point and gamma follow the Photoshop convention
Image and Colour
GradientEditor: A colour-stop gradient editor over a caller-owned list ofGradientStop: click the bar to add a stop sampled from the gradient, drag a stop to move it (never past a neighbour), drag it away or press Delete to remove it, and edit the selected stop's colour with a colour picker underneath.SampleGradientis the evaluator the bar is drawn with, interpolating in linear RGB, so the gradient on screen and the gradient a consumer applies are the same function
Image and Colour
SwatchPalette: A wrapping grid of colour swatches over a caller-owned list: click a swatch to select it, drag one to reorder the list in place, with the selection following the swatch it named. Adding, removing and editing colours is left to the host, which reads the selected index
Image and Colour
ImageCompare: Two textures of the same image, before and after, in one pannable, zoomable view, either split by a draggable divider (a wipe) or side by side in two panes that pan and zoom together. Both are placed by one caller-ownedImageCanvasState, so they line up to the pixel
Image and Colour
CropOverlay: A crop rectangle drawn over anImageCanvas, with a dimmed surround, a composition guide (the rule of thirds, or throughCropOverlayOptionsthe golden ratio, a golden spiral, diagonals, triangles or a grid, the asymmetric ones flippable four ways;CropGuidesdraws the same lines anywhere else), edge and corner handles, an optional aspect lock and an optional rotate handle. The crop lives in image pixels as aCropRectand is kept inside the image; dragging outside it pans the canvas, and the wheel zooms it
Image and Colour
TransformBox: A rectangle with corner and edge handles in its own frame, drawn through a caller-suppliedMatrix3x2to the screen, which moves, resizes and scales it, and withTransformBoxOptions.Skewon, skews it when an edge is Ctrl-dragged, and withTransformBoxOptions.Distorton, moves a Ctrl+Shift-dragged corner alone. A crop window passes the image's rectangle on screen; a layer passes its own placement composed with that, so the handles sit on the layer's turned corners. It knows nothing about what it frames: a caller with its own rule, such as an aspect preset, suppliesTransformBoxOptions.Resize. See Transform Box below
Image and Colour
Viewport3D: A 3D view drawn through the host'sIRenderer3Dinto a render target the widget owns, under an orbit camera held in a caller-ownedViewport3DState. Drag to orbit, middle-drag or Shift+drag to pan, scroll to dolly. Your callback gets aViewport3DFramewith the renderer, the target and the view-projection to draw with. On a backend without 3D it draws an empty frame of the same size and returnsfalsePixelLoupe: A magnified grid of the pixels around the pointer while it is over anImageCanvas, with the centre pixel outlined and read out as coordinates, RGBA and hex. The loupe is passive: it takes pixels from a callback you supply, never reads a texture back, and never takes a click, so the canvas keeps its pan and zoom
Layout and Containers
DividerContainer/DividerZone: A retained container divided into draggable zones, with persistable sizes; containers nestGrid:RowMajorGridandColumnMajorGridlayouts with measured, delegate-drawn cellsTabPanel: Tabbed interface with closable, reorderable tabs and dirty indicatorsCard: A scoped elevated panel that draws its shadow and rounded background behind whatever theusingblock rendersTree: CollapsibleBranchand terminalLeafnodes, with connector lines drawn between themReorderableTree: Rows the caller draws, laid out as a tree and dragged to reorder them or move them in and out of containers. Reports the move rather than applying it. See Reorderable Tree belowImageCanvas: A pannable, zoomable image canvas with a checkerboard backing for transparencyAssetBrowser: A virtualized grid of thumbnail tiles over a caller-ownedAssetBrowserState, with click, Ctrl+click and Shift+click selection, arrow-key focus, Ctrl+wheel tile resizing, double-click or Enter to activate, and dragging the selection out as a payload a drop target reads withTryAcceptAssetPayload. Only the visible rows ask for a label or thumbnail, so fifty thousand assets cost a screenfulToolbar/ToolbarButton/ToolbarToggleButton/ToolbarSeparator: A horizontal strip of buttons, each holding a glyph and a label inside one frame — glyph leading, glyph above with the label centred beneath, glyph only (the label becomes the tooltip) or label only. See Toolbar belowOverlayHost/OverlayLayer: A z-ordered registry for retained overlays — toasts, sheets, drawers — that must paint above the rest of the frame in a predictable orderPropertyGrid: A two-column grid of labelled editors — name on the left, editor on the right — covering every scalar, vector, color, path and list type, with collapsible sections. See Property Grid belowScopedId/ScopedDisable: RAII scopes for the ID stack and for disabling a block of UI
Mobile and Navigation
SwipeableListItem: A row that slides aside to reveal actions on either edge, snapping open or shut on release; a long swipe commits the outermost action without a second tapCarousel: Pages dragged or flicked sideways one at a time, with clickable page dots. A quick flick turns the page even when the drag was short, and never skips a pagePickerWheel: A column of items on a turning cylinder, over strings or a stepped range of whole numbers, optionally wrapping. Flicks coast and settle on the nearest item; a click turns a neighbouring row to the middleTimePicker: Hour and minute wheels, plus an AM/PM wheel on a twelve-hour clock, with an optional minute stepPullToRefresh: A scrolling region that refreshes when pulled down from its top, holding open with a spinner until the caller reports the refresh finished. Opened in ausingblockLongPressMenu: A menu opened by holding something down, or right-clicking it; the target shrinks while held and bumps as the menu opensToaster: Snackbar messages queued one at a time at the bottom of the window, each with an optional action such as Undo. A message stays while hovered, and one with no duration stays until dismissedActionSheet: A stack of choices that slides up from the bottom with a separate Cancel button; destructive choices are drawn in the error colour, and a tap on the dimming or Escape cancelsBottomSheet: A panel dragged up from the bottom between peek, half and full heights. A flick carries it to the height it is heading for, and a drag below half the peek height closes itNavigationDrawer: A panel that slides in from the left over a dimmed page, opened by a button or by swiping in from the window's edge, and closed by a tap or drag on the dimmingSearchOverlay: A full-window search page over a list of items, ranked by fuzzy match as you type, with arrow keys to move the highlight, Enter to choose and Escape or the back button to leaveFloatingActionButton/SpeedDial: A round button pinned to a corner of the window, and one that fans out labelled actions above itBottomNavigationBar: A row of destinations at the foot of the window, with a sliding indicator under the chosen one. It can drive aTabPaneldirectly; set the panel'sShowTabStripto false so the bar is its only tab stripAppBar: A title bar with a leading button and trailing actions, which hides as the content scrolls down and returns as soon as it scrolls back upExpandableListItem/Accordion: A row that opens to show more beneath it, its height animating as it opens and closes. AnAccordionkeeps one open at a time unlessAllowMultipleis setInfiniteList: A virtualized list that asks the caller for the next page once scrolled withinThresholdof its end, shows a loading row while the page arrives, and asks only once per pageStickyHeaderList: A scrolling list of sections whose current header stays pinned to the top, pushed up by the next one as it arrives. Opened in ausingblock, withSection(title)before each section's rowsTutorial: A coach mark tour ofCoachMarkSteps, each dimming the window around a widget the caller named withTargetafter drawing it and explaining it in a callout with Next and Skip
The overlays (Toaster, ActionSheet, BottomSheet, NavigationDrawer, SearchOverlay and Tutorial) are objects created over an OverlayHost, which the caller renders once per frame after the rest of the window. Each keeps its arithmetic in an ImGui-free state class, as the widgets above do.
Motion and Gestures
Tween/Spring/Easing: Frame-rate independent time-based interpolation, a damped harmonic oscillator that chases a target, and the easing curves to shape themInertialScroll: A one-dimensional scroll offset that coasts after release, for carousels, pickers and long listsGestureDetector/GestureMachine: Claims a region and reports tap, double-tap, long-press, swipe and pan over itHexa-backed widgets: Thin adapters over
Hexa.NET.ImGui.Widgets— spinners, buffering bars, splitters, toggle/transparent/inline buttons, an icon tree node, an enum combo, text/image alignment helpers, tooltips, breadcrumbs, a date/year picker, a flame graph, a file tree view, stateful file/rename/message dialogs, and a docked-window base class. See Hexa-backed Widgets below.Callback-driven editors:
Sequencer(an editable clip timeline),CurveEditor(a multi-curve graph, or a singleCurveDatacurve), andBezierEditor(a cubic easing curve) — driven by aSequenceSource/CurveSourceyou subclass, or by aCurveData/BezierControlPointsvalue. See Callback-driven Editors below.
Installation
To install ImGuiWidgets, you can add the library to your .NET project using the following command:
dotnet add package ktsu.ImGui.Widgets
Usage
To use ImGuiWidgets, you need to include the ktsu.ImGui.Widgets namespace in your code:
using ktsu.ImGui.Widgets;
Then, you can start using the widgets provided by ImGuiWidgets in your ImGui-based applications.
Examples
Here are some examples of using ImGuiWidgets:
Knobs
Knobs are useful for creating dial-like controls:
float value = 0.5f;
float minValue = 0.0f;
float maxValue = 1.0f;
ImGuiWidgets.Knob("Knob", ref value, minValue, maxValue);
Radial Progress Bar
The RadialProgressBar widget displays circular progress indicators perfect for loading states, progress tracking, countdowns, and timers:
float progress = 0.65f; // Progress from 0.0 to 1.0
// Basic usage - displays with default size and settings (clockwise from top, percentage text)
ImGuiWidgets.RadialProgressBar(progress);
// Custom size (radius in pixels)
ImGuiWidgets.RadialProgressBar(progress, radius: 50);
// Custom thickness
ImGuiWidgets.RadialProgressBar(progress, radius: 50, thickness: 10);
// Without text in center
ImGuiWidgets.RadialProgressBar(progress, 50, 0, 32, ImGuiRadialProgressBarOptions.NoText);
// Counter-clockwise direction (default is clockwise)
ImGuiWidgets.RadialProgressBar(progress, 50, 0, 32, ImGuiRadialProgressBarOptions.CounterClockwise);
// Start at bottom instead of top
ImGuiWidgets.RadialProgressBar(progress, 50, 0, 32, ImGuiRadialProgressBarOptions.StartAtBottom);
// Combine options: counter-clockwise starting at bottom
ImGuiWidgets.RadialProgressBar(progress, 50, 0, 32,
ImGuiRadialProgressBarOptions.CounterClockwise | ImGuiRadialProgressBarOptions.StartAtBottom);
// Animated progress example
float animatedProgress = 0.0f;
void UpdateProgress(float deltaTime)
{
animatedProgress += deltaTime * 0.2f;
if (animatedProgress > 1.0f) animatedProgress = 0.0f;
ImGuiWidgets.RadialProgressBar(animatedProgress);
}
Text Display Modes
The RadialProgressBar supports three text display modes:
// Percentage mode (default) - displays "65%"
ImGuiWidgets.RadialProgressBar(0.65f);
// Time mode - displays time in MM:SS or HH:MM:SS format
ImGuiWidgets.RadialProgressBar(
progress: 0.5f,
textMode: ImGuiRadialProgressBarTextMode.Time,
timeValue: 150.0f // Displays "02:30"
);
// Time mode with hours - displays "01:05:30"
ImGuiWidgets.RadialProgressBar(
progress: 0.7f,
textMode: ImGuiRadialProgressBarTextMode.Time,
timeValue: 3930.0f // 1 hour, 5 minutes, 30 seconds
);
// Custom text mode - displays any string you provide
ImGuiWidgets.RadialProgressBar(
progress: 0.3f,
textMode: ImGuiRadialProgressBarTextMode.Custom,
customText: "Loading..."
);
Countdown Timer
Use RadialCountdown for countdown timers showing time remaining:
float countdownTime = 300.0f; // 5 minutes in seconds
const float CountdownTotal = 300.0f;
bool isRunning = false;
// Update countdown
if (isRunning && countdownTime > 0.0f)
{
countdownTime -= deltaTime;
if (countdownTime < 0.0f)
{
countdownTime = 0.0f;
isRunning = false;
}
}
// Display countdown - shows time remaining (e.g., "05:00", "04:30", etc.)
ImGuiWidgets.RadialCountdown(countdownTime, CountdownTotal);
// With custom options
ImGuiWidgets.RadialCountdown(
countdownTime,
CountdownTotal,
radius: 60,
thickness: 12,
segments: 64,
options: ImGuiRadialProgressBarOptions.CounterClockwise
);
// Reset button
if (ImGui.Button("Reset"))
{
countdownTime = CountdownTotal;
isRunning = false;
}
Count-Up Timer
Use RadialCountUp for timers showing elapsed time:
float elapsedTime = 0.0f;
const float TotalTime = 180.0f; // 3 minutes
bool isRunning = false;
// Update timer
if (isRunning && elapsedTime < TotalTime)
{
elapsedTime += deltaTime;
if (elapsedTime > TotalTime)
{
elapsedTime = TotalTime;
isRunning = false;
}
}
// Display count-up timer - shows elapsed time (e.g., "00:00", "00:15", etc.)
ImGuiWidgets.RadialCountUp(elapsedTime, TotalTime);
// With custom size and options
ImGuiWidgets.RadialCountUp(
elapsedTime,
TotalTime,
radius: 70,
options: ImGuiRadialProgressBarOptions.StartAtBottom
);
// Start/stop controls
if (ImGui.Button(isRunning ? "Stop" : "Start"))
{
isRunning = !isRunning;
}
if (ImGui.Button("Reset"))
{
elapsedTime = 0.0f;
isRunning = false;
}
Advanced Timer Examples
// Pomodoro timer (25 minutes work, 5 minutes break)
const float WorkDuration = 1500.0f; // 25 minutes
const float BreakDuration = 300.0f; // 5 minutes
float currentTime = WorkDuration;
bool isWorkSession = true;
if (isWorkSession)
{
ImGuiWidgets.RadialCountdown(currentTime, WorkDuration, radius: 80);
}
else
{
ImGuiWidgets.RadialCountdown(currentTime, BreakDuration, radius: 80);
}
// Stopwatch with custom display
float stopwatchTime = 0.0f;
ImGuiWidgets.RadialProgressBar(
progress: 0.0f, // No progress bar fill
radius: 60,
textMode: ImGuiRadialProgressBarTextMode.Time,
timeValue: stopwatchTime,
options: ImGuiRadialProgressBarOptions.NoText // Hide text if desired
);
ImGui.Text($"Elapsed: {stopwatchTime:F2}s");
// Combined progress and time display
float taskProgress = 0.35f;
float taskTimeRemaining = 120.0f; // 2 minutes remaining
ImGui.Columns(2);
ImGuiWidgets.RadialProgressBar(taskProgress);
ImGui.TextUnformatted("Progress");
ImGui.NextColumn();
ImGuiWidgets.RadialProgressBar(
taskProgress,
textMode: ImGuiRadialProgressBarTextMode.Time,
timeValue: taskTimeRemaining
);
ImGui.TextUnformatted("Time Remaining");
ImGui.Columns(1);
SearchBox
The SearchBox widget provides a powerful search interface with multiple filter type options:
// Static fields to maintain filter state between renders.
// The options record carries the label, filter type, match options,
// and hint/tooltip/context-menu toggles. Right-click updates it in place.
private static string searchTerm = string.Empty;
private static SearchBoxOptions searchOptions = new(Label: "##BasicSearch", FilterType: TextFilterType.Glob);
private static SearchBoxRankedOptions rankedOptions = new(Label: "##RankedSearch");
// List of items to search
var items = new List<string> { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
// Basic search box with right-click context menu for filter options
ImGuiWidgets.SearchBox(ref searchOptions, ref searchTerm);
// Display results
if (!string.IsNullOrEmpty(searchTerm))
{
ImGui.TextUnformatted($"Search results for: {searchTerm}");
}
// Search box that returns filtered results directly
var filteredResults = ImGuiWidgets.SearchBox(
ref searchOptions,
ref searchTerm,
items, // Collection to filter
item => item).ToList(); // Selector function to extract string from each item
// Ranked search box for fuzzy matching and ranked results
var rankedResults = ImGuiWidgets.SearchBoxRanked(
ref rankedOptions,
ref searchTerm,
items,
item => item).ToList();
TabPanel
TabPanel creates a tabbed interface with support for closable tabs, reordering, and dirty state indication:
// Create a tab panel with closable and reorderable tabs
var tabPanel = new ImGuiWidgets.TabPanel("MyTabPanel", true, true);
// Add tabs with explicit IDs (recommended for stability when tabs are reordered)
string tab1Id = tabPanel.AddTab("tab1", "First Tab", RenderTab1Content);
string tab2Id = tabPanel.AddTab("tab2", "Second Tab", RenderTab2Content);
string tab3Id = tabPanel.AddTab("tab3", "Third Tab", RenderTab3Content);
// Draw the tab panel in your render loop
tabPanel.Draw();
// Methods to render tab content
void RenderTab1Content()
{
ImGui.Text("Tab 1 Content");
// Mark tab as dirty when content changes
if (ImGui.Button("Edit"))
{
tabPanel.MarkTabDirty(tab1Id);
}
// Mark tab as clean when content is saved
if (ImGui.Button("Save"))
{
tabPanel.MarkTabClean(tab1Id);
}
}
void RenderTab2Content()
{
ImGui.Text("Tab 2 Content");
}
void RenderTab3Content()
{
ImGui.Text("Tab 3 Content");
}
Icons
Icons can be used to display images with various alignment options and event delegates:
float iconWidthEms = 7.5f;
float iconWidthPx = ImGuiApp.EmsToPx(iconWidthEms);
// GetOrLoadTexture returns an ImGuiAppTextureInfo; use its TextureId
ImGuiAppTextureInfo texture = ImGuiApp.GetOrLoadTexture("icon.png");
ImGuiWidgets.Icon("Click Me", texture.TextureId, iconWidthPx, ImGuiWidgets.IconAlignment.Vertical, new ImGuiWidgets.IconOptions()
{
OnClick = () => Console.WriteLine("You clicked")
});
ImGui.SameLine();
ImGuiWidgets.Icon("Double Click Me", texture.TextureId, iconWidthPx, ImGuiWidgets.IconAlignment.Vertical, new ImGuiWidgets.IconOptions()
{
OnDoubleClick = () => Console.WriteLine("You clicked twice")
});
ImGui.SameLine();
ImGuiWidgets.Icon("Right Click Me", texture.TextureId, iconWidthPx, ImGuiWidgets.IconAlignment.Vertical, new ImGuiWidgets.IconOptions()
{
OnContextMenu = () =>
{
ImGui.MenuItem("Context Menu Item 1");
ImGui.MenuItem("Context Menu Item 2");
ImGui.MenuItem("Context Menu Item 3");
},
});
Grid
The grid layout allows you to display items in a flexible grid:
float iconSizeEms = 7.5f;
float iconSizePx = ImGuiApp.EmsToPx(iconSizeEms);
ImGuiAppTextureInfo texture = ImGuiApp.GetOrLoadTexture("icon.png");
// RowMajorGrid (or ColumnMajorGrid) takes an id, the items, a measure delegate, and a draw delegate
ImGuiWidgets.RowMajorGrid(
"MyGrid",
items,
item => ImGuiWidgets.CalcIconSize(item, iconSizePx, ImGuiWidgets.IconAlignment.Vertical),
(item, cellSize, itemSize) =>
{
ImGuiWidgets.Icon(item, texture.TextureId, iconSizePx, ImGuiWidgets.IconAlignment.Vertical);
});
Color Indicator
The color indicator widget displays a color when enabled:
// color is a Hexa.NET.ImGui.ImColor (for example, from ktsu.ImGui.Styler's Color helpers)
ImColor color = Color.FromHex("#ff0000");
bool enabled = true;
ImGuiWidgets.ColorIndicator(color, enabled);
Image
The image widget allows you to display images with alignment options:
ImGuiAppTextureInfo texture = ImGuiApp.GetOrLoadTexture("image.png");
ImGuiWidgets.Image(texture.TextureId, new Vector2(100, 100));
Text
The text widget allows you to display text with alignment options:
ImGuiWidgets.Text("Hello, ImGuiWidgets!");
ImGuiWidgets.TextCentered("Hello, ImGuiWidgets!");
ImGuiWidgets.TextCenteredWithin("Hello, ImGuiWidgets!", new Vector2(100, 100));
Tree
Hierarchical data, drawn with connector lines. A Branch collapses and carries children, a Leaf is a
terminal row:
ImGuiWidgets.Tree.Branch("Fruit", () =>
{
ImGuiWidgets.Tree.Branch("Citrus", () =>
{
ImGuiWidgets.Tree.Leaf(() => ImGui.Button("Lemon"));
ImGuiWidgets.Tree.Leaf(() => ImGui.Button("Lime"));
});
ImGuiWidgets.Tree.Leaf(() => ImGui.Button("Apple"));
});
A collapsed branch never invokes its body, so there is no open-state check to write and none to forget. Branches find their parent from the innermost enclosing branch, so nothing is threaded through the callbacks. A branch with no enclosing branch is a root row and draws no connector, since it has nothing above it to join to.
Pass ImGuiTreeNodeFlags to control the node itself. These replace the default of SpanAvailWidth
rather than adding to it:
ImGuiWidgets.Tree.Branch("Collapsed by default", ImGuiTreeNodeFlags.None, () => { /* ... */ });
In a tree large enough for one closure per node per frame to matter, the state overloads let the
callback be static and capture nothing:
ImGuiWidgets.Tree.Branch("Vegetables", carrot, static item =>
ImGuiWidgets.Tree.Leaf(item, static text => ImGui.Button(text)));
Both Branch overloads have a flags form, so state and flags can be combined:
ImGuiWidgets.Tree.Branch("Vegetables", ImGuiTreeNodeFlags.DefaultOpen, carrot, static item => { /* ... */ });
The original scope form still works, and is the way to draw rows without a callback at all. It also
draws a spine at the outermost level, which a bare Branch does not:
using (var tree = new ImGuiWidgets.Tree())
{
for (int i = 0; i < 5; i++)
{
using (tree.Child)
{
ImGui.Button($"Hello, Child {i}!");
using (var subtree = new ImGuiWidgets.Tree())
{
using (subtree.Child)
{
ImGui.Button($"Hello, Grandchild!");
}
}
}
}
}
Reorderable Tree
A tree whose rows can be dragged. The caller flattens its own tree into rows, top first, leaving out the children of anything collapsed, and draws each row's content itself; the widget lays the rows out, draws where a drag would land, and reports the move on release. It never applies it, so the move goes through the caller's own model and undo history:
ReorderableTreeRow[] rows = [new(0, false), new(0, true), new(1, false), new(1, false)];
if (ImGuiWidgets.ReorderableTree("layers", rows, i => ImGui.Selectable(names[i])) is ReorderableTreeMove move)
{
// move.Row moves under move.ParentRow (-1 for the top level), into the gap move.Index.
}
The top quarter of a container row drops above it, the bottom quarter below it, and the middle half inside it. A leaf splits at the middle. Below the last row of a subtree, how far left the pointer is picks how far out the drop lands. A drop onto the dragged row or anywhere in its subtree is refused, and so is one that would leave the row where it is.
Index counts the new parent's children before the move, which is the gap the insertion line was
drawn in. When a row moves down within its own parent, its old place is among those children, so a
caller whose insert takes the final position subtracts one in exactly that case:
if (sameParent && oldIndex < move.Index)
{
index = move.Index - 1;
}
A drag starts from a press anywhere on a row once the mouse moves past ImGui's drag threshold, so a
click that does not move is left to the row's own items. Each row is marked for probes as
row{index} inside the tree's label.
Transform Box
A rectangle with handles, held in its own frame and drawn through a transform. The frame is whatever the caller's edit is measured in: fractions of an image for a crop, a layer's unit square for arranging that layer. Pass the transform from that frame to the screen, and the area the box may be held in:
ImGui.SetNextItemAllowOverlap(); // let the box take the pointer from the canvas underneath
ImGuiWidgets.ImageCanvas("canvas", texture, imageSize, canvasState, canvasSize);
Vector2 canvasMin = ImGui.GetItemRectMin();
Matrix3x2 frameToScreen = layerPlacement * imageToScreen;
TransformBoxResult result = ImGuiWidgets.TransformBox(
"layer", ref rect, frameToScreen, canvasMin, canvasMin + canvasSize,
new TransformBoxOptions { UniformCorners = true });
if (result.Released)
{
// Fold rect into the layer's placement as one undoable edit.
}
Dragging the body moves the rectangle, an edge moves that edge, and a corner moves both of its edges,
or scales about the opposite corner when UniformCorners is on; Shift inverts that. A uniform corner
scales by how far the pointer has travelled along the diagonal on screen, so a stretched frame
does not count one axis of the pointer's travel for more than the other. No side passes its
opposite: a box dragged inside out stops at MinimumScreenSize pixels.
With Skew on, pressing an edge with Ctrl held slides that edge along itself while the opposite edge
stays put, and the rectangle comes back with TransformBoxRect.Skew set: a shear about its centre,
which TransformBoxRect.Shape() returns as a matrix to fold into whatever the box frames.
Min/Max stay the unskewed rectangle and Corners() the parallelogram. A skewed box keeps its
slant when resized: the drag is carried back into the unskewed rectangle and the handle's opposite
edge or corner held where it was. The choice between stretch and skew is made at the press, and
TransformBoxResult.Skewing reports it, or on hover what a press would do.
With Distort on, pressing a corner with Ctrl and Shift held moves that corner alone, and the
rectangle comes back with TransformBoxRect.Quad set to the four corners of a quadrilateral. The
mapping from the rectangle onto it is projective, which no Matrix3x2 holds, so the box hands back
the corners and the caller builds its own transform from them; Corners() answers the
quadrilateral. From then on every handle moves corners (a corner itself, an edge its two, the body
all four), and the quadrilateral is held convex, with the press's winding and no side shorter than
MinimumScreenSize, so a projective transform onto it stays defined. A caller can set Quad to
show a box it distorted earlier. TransformBoxResult.Distorting reports the choice as Skewing
does.
Three things to know when using it:
- It takes the pointer only over itself. The hit area is submitted only while the pointer is over
a handle or the body, or while one is held, so a press anywhere else reaches the item underneath —
an
ImageCanvas's pan, for example. That item must be submitted withSetNextItemAllowOverlap, or it keeps the hover and the box can never be pressed. - A drag is measured in the frame as it was at the press. A caller whose edit moves the frame itself, as moving a layer does when the frame is the layer's placement, gets the same answer whichever frame it passes while the drag goes on. The simplest pattern is to keep passing the frame from the press and the rectangle the drag returns, and fold the rectangle in on release.
- Hit-testing is on screen. The grab radius is screen pixels however the frame is stretched or turned, and inside a box too small on screen for its handles, each handle's reach shrinks to a quarter of its side so there is always a body to move it by.
Scoped Id
The scoped ID utility class helps in creating scoped IDs for ImGui elements and ensuring they get popped appropriately:
using (new ImGuiWidgets.ScopedId())
{
ImGui.Button("Hello, Scoped ID!");
}
Scoped Disable
Temporarily disable UI elements within a scope. Disabled elements are visually grayed out and non-interactive:
bool shouldDisable = true;
// Disable buttons within this scope
using (new ScopedDisable(shouldDisable))
{
ImGui.Button("I'm disabled!");
ImGui.InputText("Disabled Input", ref someText, 256);
}
// Elements outside the scope are enabled normally
ImGui.Button("I'm enabled!");
// Nested disables work as expected (per Dear ImGui rules)
using (new ScopedDisable(false))
{
ImGui.Text("Enabled section");
using (new ScopedDisable(true))
{
ImGui.Button("Disabled button");
}
}
Note: As per Dear ImGui documentation, nested BeginDisabled calls cannot re-enable an already disabled section - a single BeginDisabled(true) in the stack is enough to keep everything disabled.
Combo
Type-safe combo box widgets for enums, strings, and strong strings:
// Enum combo box
enum Season { Spring, Summer, Fall, Winter }
Season selectedSeason = Season.Summer;
if (ImGuiWidgets.Combo("Season", ref selectedSeason))
{
Console.WriteLine($"Selected: {selectedSeason}");
}
// String combo box
string selectedFruit = "Apple";
var fruits = new Collection<string> { "Apple", "Banana", "Cherry", "Date" };
if (ImGuiWidgets.Combo("Fruit", ref selectedFruit, fruits))
{
Console.WriteLine($"Selected: {selectedFruit}");
}
// Strong string combo box (using ktsu.Semantics.Strings)
using ktsu.Semantics.Strings;
MyStrongString selected = new("Value1");
var options = new Collection<MyStrongString>
{
new("Value1"),
new("Value2"),
new("Value3")
};
if (ImGuiWidgets.Combo("Option", ref selected, options))
{
Console.WriteLine($"Selected: {selected}");
}
DividerContainer
Create resizable layouts with draggable dividers between content regions:
// Create a column-based divider container (side-by-side zones)
var dividerContainer = new ImGuiWidgets.DividerContainer(
"MyContainer",
ImGuiWidgets.DividerLayout.Columns
);
// Add zones with: id, initial size (relative weight), resizable, and a tick delegate (receives delta time)
dividerContainer.Add("Left Panel", 0.33f, true, dt =>
{
ImGui.Text("Left side content");
ImGui.Button("Left Button");
});
dividerContainer.Add("Right Panel", 0.67f, true, dt =>
{
ImGui.Text("Right side content");
ImGui.Button("Right Button");
});
// Tick the container each frame in your render loop
dividerContainer.Tick(deltaTime);
// For a stacked (top/bottom) layout, use DividerLayout.Rows:
var stackedContainer = new ImGuiWidgets.DividerContainer(
"StackedContainer",
ImGuiWidgets.DividerLayout.Rows
);
stackedContainer.Add("Top Panel", 0.5f, true, dt =>
{
ImGui.Text("Top content");
});
stackedContainer.Add("Bottom Panel", 0.5f, true, dt =>
{
ImGui.Text("Bottom content");
});
stackedContainer.Tick(deltaTime);
The dividers can be dragged by the user to resize the content regions dynamically.
Piano Keyboard
The layout says which notes to draw; both ends must be white keys. Notes are plain MIDI numbers
(middle C is 60, named C4), and nothing makes a sound: the widget reports what was played, and
the host sends it wherever sound comes from.
// Two octaves, C3 to C5. Immutable, so one layout can be shared.
ImGuiWidgets.PianoKeyboardLayout layout = new(48, 72);
// Each frame. Width 0 fills the row; notes held elsewhere (MIDI input, a sequencer) light up.
ImGuiWidgets.PianoKeyEvent played = ImGuiWidgets.PianoKeyboard("Keys", layout, new Vector2(0, 90), heldNotes);
if (played.HasNoteOff)
{
synth.NoteOff(played.NoteOff);
}
if (played.HasNoteOn)
{
synth.NoteOn(played.NoteOn, played.Velocity);
}
The pointer holds one note at a time. Dragging onto another key stops the old note and starts the
new one in the same event, so handle the note-off first. Velocity runs from 1 at the back of a key
to 127 at its front edge. HitTest, GetKeySpan, VelocityAt and NoteName expose the geometry
for a piano roll's rows or labels, and each key is marked for probes as {label}/{note name}, for
example Keys/C#4.
Property Grid
ImGuiWidgets.PropertyGrid lays out one labelled editor per property in a two-column, resizable
table. It is immediate mode like the rest of the library: it holds no model, and each row edits a
variable passed by reference.
using (ImGuiWidgets.PropertyGrid grid = new("Settings"))
{
using (grid.Section("Basics"))
{
grid.Value("Visible", ref visible); // bool
grid.Value("Quantity", ref quantity, 0, 100); // int, clamped to a range
grid.Value("Serial", ref serial); // long
grid.Value("Weight", ref weight); // float
grid.Value("Tolerance", ref tolerance); // double
grid.Value("Name", ref name); // string
grid.Enum("Mode", ref mode); // any enum
}
using (grid.Section("Geometry"))
{
grid.Value("Offset", ref offset); // System.Numerics.Vector2
grid.Value("Scale", ref scale); // System.Numerics.Vector3
grid.Value("Origin", ref origin); // ImGuiWidgets.DoubleVector2
grid.Value("Extent", ref extent); // ImGuiWidgets.DoubleVector3
}
grid.Value("Tint", ref tint); // ktsu.Semantics.Color.Color
grid.FilePath("Config", ref configPath);
grid.DirectoryPath("Output", ref outputFolder);
grid.ImagePath("Icon", ref iconPath); // with a thumbnail beneath it
grid.List("Tags", tags); // a list of any of the above
if (grid.Changed)
{
Save();
}
}
One overloaded Value row covers every scalar, vector and color type; Enum, the three path rows
and List cover the rest. Every row returns whether it changed this frame, and Changed
accumulates those answers so the whole grid can be tested once.
Section returns a scope that closes the section when it is disposed, so there is nothing to
remember to call and nothing to test: a collapsed section holds its rows back itself, and the rows
inside it are written exactly as they are anywhere else. Sections nest, and a collapsed one holds
back everything inside it however deeply nested. SectionScope.IsOpen says whether the section is
expanded, which is worth reading only to skip work that costs something to prepare before a row can
be called.
A List row draws one editor per element, a + to append and an x on each element to remove it.
Any row method can be an element editor, so List has an overload per supported element type, plus
FilePathList, DirectoryPathList and ImagePathList for the ones whose element type is also a
string. A list of some other type takes an editor and a factory:
grid.List("Points", points, (string label, ref Vector2 value) => grid.Value(label, ref value), () => Vector2.Zero);
Paths and thumbnails
This library does not open file dialogs or upload textures, so the path rows delegate both:
ImGuiWidgets.PropertyGridOptions options = new()
{
OnBrowse = request =>
{
// Hexa's dialogs are asynchronous, so the request is completed from the close callback.
ImGuiWidgets.OpenFileDialog dialog = new();
dialog.Show(outcome => request.Complete(outcome.Path?.ToString()));
},
ThumbnailResolver = path => ImGuiApp.GetOrLoadTexture(path.As<AbsoluteFilePath>()).TextureId,
};
OnBrowse receives the row's label, what it is asking for (File, Directory or Image) and the
path it currently holds. Browsing is asynchronous by nature — a dialog outlives the frame that
opened it — so the request carries no reference to the value: whenever Complete is called, the row
adopts the answer the next time it is drawn. Completing with null leaves the value alone, which is
what a cancelled dialog should do. Without an OnBrowse the browse button is disabled and paths can
still be typed; without a ThumbnailResolver an image row draws an empty preview frame, so its
height does not change once a picture appears.
The other options are ReadOnly (every row drawn disabled), LabelColumnWeight /
LabelColumnWidth, ListsStartExpanded, ThumbnailSize, and the printf-style FloatFormat /
DoubleFormat.
Data Table
DataTable draws typed rows, only the ones on screen, with sortable headers and a filter box under each. A person moves an active cell with the arrow keys, Tab and Page Down, and edits a cell by double-clicking it, pressing F2, or typing. Enter commits and moves down, and Escape cancels.
The table never writes to your rows. Each editable column gets an OnEdit callback, and you apply the edit, which is what makes undo straightforward:
private static readonly List<Part> parts = LoadParts();
private static readonly ImGuiWidgets.DataTableState<Part> state = new(
[
new ImGuiWidgets.DataTableColumn<Part, string>
{
Label = "Name",
Value = part => part.Name,
OnEdit = edit => edit.Row.Name = edit.NewValue,
},
new ImGuiWidgets.DataTableColumn<Part, int>
{
Label = "Quantity",
Value = part => part.Quantity,
},
]);
ImGuiWidgets.DataTable("parts", parts, state);
A column with no OnEdit is read-only. Strings, numbers, bool and enums get built-in editors, and any other type supplies an Editor.
An edited row stays where it is until you call state.Refresh(), even if its new value sorts elsewhere, so it doesn't jump away while someone is working on it. The table rebuilds by itself when the sort, a filter, or the row count changes.
Pass DataTableOptions.Keybindings to drive the keys from a ktsu.Keybinding keymap, after registering the commands with ImGuiWidgets.DataTableCommands.Register.
Spectrum Analyzer
The FFT stays with the host: hand in the N / 2 + 1 bin magnitudes of a real FFT, in decibels, and
the state folds them into logarithmically spaced bands. A band takes its loudest bin, and a band too
narrow to hold one reads the level interpolated at its centre. Bars rise at once and fall at
BarFallRate; each band's peak holds for PeakHoldSeconds, then falls at PeakFallRate.
// Kept across frames, like any other widget state.
ImGuiWidgets.SpectrumAnalyzerState spectrum = new(bandCount: 32, minFrequency: 20f, maxFrequency: 20000f);
// Each frame: fold in this frame's bins, advance by the frame's delta time, and draw.
ImGuiWidgets.SpectrumAnalyzer("Output", spectrum, binsDb, sampleRate: 48000f, new Vector2(480, 180));
// Or draw a line instead of bars, and advance the state yourself.
spectrum.Update(binsDb, 48000f, deltaSeconds);
ImGuiWidgets.SpectrumAnalyzer("Output", spectrum, new Vector2(480, 180), style: ImGuiWidgets.SpectrumAnalyzerStyle.Line);
GetBandIndex, GetBandCenter and FrequencyToPosition expose the log-frequency axis for hit
testing or labels.
Envelope Editor
Envelope is a DAHDSR envelope: delay, attack, hold, decay and release in seconds, a sustain level
from 0 to 1, and a tension from -1 to 1 on each of the three curved segments, where 0 is a straight
line. LevelAt(time, noteOffTime) is the evaluator the editor draws, so the curve on screen is the
curve your synth applies.
ImGuiWidgets.Envelope envelope = ImGuiWidgets.Envelope.Adsr(0.01f, 0.2f, 0.7f, 0.5f);
// Returns true on any frame the envelope changed. The time span is the seconds across the width.
if (ImGuiWidgets.EnvelopeEditor("Amp", ref envelope, new Vector2(0, 160), timeSpan: 3f))
{
voice.Envelope = envelope;
}
// Hide the delay and hold handles for a plain ADSR.
ImGuiWidgets.EnvelopeEditor("Filter", ref filterEnvelope, showDelayAndHold: false);
float level = envelope.LevelAt(secondsSinceNoteOn, noteOffTime: secondsHeld);
Drag a breakpoint to retime its segment (and, for the decay end and sustain, set the sustain level);
drag a tension handle vertically to bend its segment, and right-click it to straighten it. Values
that are not finite or are out of range are repaired on the first frame and reported as a change.
Each handle is marked for probes as <label>/attack, <label>/decayTension and so on.
Parametric EQ
The caller owns the bands and the response. Drag a node to move its band, sideways for frequency
and vertically for gain; the wheel over a node changes its Q. LowCut, HighCut and Notch have no
gain, so their nodes sit on the 0 dB line and only move sideways. The widget returns true on any
frame a band's value actually changed, so a held pointer does not mint undo entries.
ImGuiWidgets.EqBand[] bands =
[
new(40f, 0f, ImGuiWidgets.EqBand.DefaultQ, ImGuiWidgets.EqBandType.LowCut),
new(250f, -3f, 1.2f),
new(8000f, 2f, ImGuiWidgets.EqBand.DefaultQ, ImGuiWidgets.EqBandType.HighShelf),
];
ImGuiWidgets.LogFrequencyAxis axis = new(20f, 20000f);
int selected = -1;
// Each frame. Plot your own DSP's response if it has one, so the curve is the one you apply.
if (ImGuiWidgets.ParametricEq("EQ", bands, f => ImGuiWidgets.EqResponse.TotalDb(bands, f, 48000f), axis, ref selected, new Vector2(480, 220)))
{
// Recompute your filters.
}
Pass a SpectrumAnalyzerState's own Axis to put the EQ on exactly the analyzer's frequency scale:
a frequency then lands at the same fraction of the width in both. Each node is probe-visible as
{label}/band{i}.
Log View
The log is a list you own and append to, oldest first; the widget never copies it. A
LogViewState per view holds the filter, the shown levels, collapsing, following and the
selection, and indexes the log incrementally: appending lines filters only those lines. Adapt your
own logger to LogEntry; nothing here references a logging framework.
List<LogEntry> log = [];
ImGuiWidgets.LogViewState logState = new();
ImGuiWidgets.LogViewOptions logOptions = new() { Size = new Vector2(0, 300) };
log.Add(new LogEntry(LogViewLevel.Warning, "frame hitch: 41 ms", DateTime.Now, "render"));
// Each frame.
ImGuiWidgets.LogView("Console", log, logState, logOptions);
Rows are virtualized through VirtualTable, so a log of a hundred thousand lines costs only the
rows on screen. The filter is the same SearchBox used elsewhere, matched against each message.
While the list is hovered or focused, Ctrl+C copies the selection, Ctrl+A selects every row and
Escape clears it; a right click offers Copy, Copy all visible and Clear selection. OnCopy takes
the copied text instead of the clipboard.
The index sees appends and a log that shrinks. A ring buffer that drops old lines as it adds new
ones keeps its length, so tell the state with EntriesRemovedFromStart(count); after editing
entries in place, call Invalidate(). The widget is probe-visible as {label}, its filter as
{label}/filter, its toggles by their captions ({label}/Warn, {label}/Follow) and its rows as
{label}/rows/[i].
Step Grid
The pattern is yours, row-major and edited in place: cell (row, step) is
steps[row * stepCount + step]. The grid never reflows, so column i is always step i, and it
reserves exactly its label column plus the cells; put a long pattern in a child window of your own.
// Kept across frames: four voices of sixteen steps.
bool[] pattern = new bool[4 * 16];
string[] voices = ["Kick", "Snare", "Hat", "Clap"];
// Each frame. The host advances playingStep from its own clock; -1 highlights nothing.
if (ImGuiWidgets.StepGrid("Drums", pattern, rows: 4, stepCount: 16, playingStep, rowLabels: voices))
{
// At least one cell changed this frame.
}
A press toggles the cell it lands on, and the rest of the drag paints that cell's new value, so one
gesture either fills or clears a run and never flickers cells back and forth. stepsPerBeat
(default 4) shades each beat's first column, and cellSize defaults to a square of the frame height.
Cells are probed as "{label}/r{row}s{step}".
Toolbar
A toolbar is a using scope; buttons and separators submitted inside it are laid out left to right
on one row. Each button draws its glyph and its label inside the same frame, so a glyph is any
string in the current font — merge an icon font such as Material Icons or a Nerd Font to use icons.
using (ImGuiWidgets.Toolbar("##edit"))
{
if (ImGuiWidgets.ToolbarButton("Open", "\uE2C7", new() { Shortcut = "Ctrl+O" }))
{
OpenFile();
}
ImGuiWidgets.ToolbarSeparator();
ImGuiWidgets.ToolbarToggleButton("Bold", "\uE238", ref bold, new() { Layout = ToolbarButtonLayout.GlyphOnly });
}
// A two-line strip: every button puts its label centred under its glyph.
using (ImGuiWidgets.Toolbar("##transport", new ToolbarOptions { Layout = ToolbarButtonLayout.GlyphAbove }))
{
ImGuiWidgets.ToolbarButton("Play", "\uE037", new() { MinWidth = 56 });
ImGuiWidgets.ToolbarButton("Stop", "\uE047", new() { MinWidth = 56 });
}
ToolbarButtonLayout picks where the label goes:
| Layout | Glyph | Label |
|---|---|---|
GlyphLeading (default) |
left | right of the glyph, on the same line |
GlyphAbove |
top, centred | below the glyph, centred |
GlyphOnly |
centred | shown as the tooltip unless one is set |
LabelOnly |
not drawn | centred |
A button takes its toolbar's layout unless it sets its own. A single-line toolbar has no room for
a two-line button, so GlyphAbove falls back to GlyphLeading there; a single-line button in a
GlyphAbove toolbar is centred vertically in the taller row. A missing glyph or label collapses
the layout to the part that is present. Buttons also work outside a toolbar, where they size to
themselves. ToolbarGeometry holds the layout arithmetic and takes plain sizes, so it can be used
or tested without an ImGui context.
Each button is probed under its label inside the toolbar's id ("##edit/Open"), its tooltip text
under a name ending Open/tooltip, and the strip itself under its id.
Hexa-backed Widgets
These widgets are thin adapters that delegate to Hexa.NET.ImGui.Widgets rather than reimplementing rendering logic:
Spinner: Indeterminate loading spinner animated from the ImGui frame timeBufferingBar: Horizontal bar filled left-to-right in proportion to a valueHorizontalSplitter/VerticalSplitter: Draggable splitters that adjust a bound height/width within min/max limitsToggleSwitch: Sliding on/off switchToggleButton: Button that shows a highlight ring while selectedTransparentButton: Button with no background until hoveredInlineButton: Compact button anchored inside an existing rectangle, for rows and headersIconTreeNode: Tree node with a colored icon glyph before its labelEnumCombo<T>: Combo box listing every member of an enum typeTextCenteredV/TextCenteredH/TextCenteredVH: Text centered vertically, horizontally, or bothImageCenteredV/ImageCenteredH/ImageCenteredVH: Image centered vertically, horizontally, or bothImageScaleTo: Image scaled to fit inside a destination box while preserving aspect ratioTooltip: Shows a tooltip for the preceding item while it is hoveredBreadcrumb: Clickable breadcrumb trail from a separator-delimited pathDatePicker: Calendar control for picking a dateYearPicker: Grid control for picking a yearFlameGraph: Flame graph of hierarchical timing samplesFileTreeView: Navigable tree of the filesystem rooted at the machine's drivesOpenFileDialog/SaveFileDialog/OpenFolderDialog: Stateful dialogs for choosing existing files, a save destination, or a folderRenameDialog: Renames or moves a file, reporting success or failure without throwingDialogMessageBox/ShowMessageBox: A movable-window-style and a popup-style message box, respectivelyDockedWindow: Abstract base for a floating window the user can drag into the dockspaceDrawDeferredDocked()creates — subclass it, overrideTitleandDrawContent(), then callShow()/Close(). It is dockable, not auto-docked: it opens floating and stays there until the user drags it in
Material Icons font: DatePicker (Material CalendarToday, U+E935) and FileTreeView (Home U+E9B2, Computer U+E31E) render placeholder boxes unless a Material Icons font is registered in the atlas. OpenFileDialog, SaveFileDialog and OpenFolderDialog need the same font for their toolbar, breadcrumb and file-tree glyphs. Register it via FontHelper.AddCustomFont(io, fontData, size, FontHelper.GetMaterialIconRanges(), mergeWithPrevious: true) — not via ImGuiAppConfig.Fonts, which applies the Nerd Font mapping and leaves the glyphs unmapped. See examples/ImGuiAppDemo for a worked example. YearPicker, RenameDialog, DialogMessageBox and ShowMessageBox require no icon font.
Overlapping widgets: Seven Hexa-backed widgets look like duplicates of an existing ktsu widget. Five are not: HorizontalSplitter/VerticalSplitter is a single drag handle where DividerContainer is a retained layout container; IconTreeNode is a single node with an icon glyph where Tree.Branch is a whole collapsible subtree with connector lines; BufferingBar/Spinner are determinate-linear and indeterminate where RadialProgressBar/SkeletonLine are determinate-radial and a shimmering placeholder; and the TextCentered*/ImageCentered* families each cover axes and overloads the other does not. Two do overlap: prefer Switch over ToggleSwitch (it animates from ImGui.GetIO().DeltaTime rather than Hexa's animation clock, and draws its own label), and prefer Combo over EnumCombo unless you need Hexa's display-name overrides. Nothing is obsoleted — that is a breaking change — but new code should reach for the preferred one, and the "Hexa vs ktsu" comparison tab in examples/ImGuiWidgetsDemo shows the pairs side by side. Every widget in both families marks itself for UI probes, so a test addresses any of them by name: its label or id, or a kind name such as spinner or image for one that takes neither, separated with ScopedId when two share a window.
Deferred drawing: The dialogs above and DockedWindow only draw when a per-frame pump runs. Call ImGuiWidgets.DrawDeferred() once per frame (at the end of OnRender) to draw every open dialog, message box and popup and advance Hexa's animation clock; call ImGuiWidgets.DrawDeferredDocked() instead if you use DockedWindow — it creates a dockspace over the main viewport and draws every registered docked window, and it already does everything DrawDeferred() does, so call only one of the two per frame (calling both draws every dialog twice). It requires ImGuiConfigFlags.DockingEnable, which ImGuiAppConfig.EnableDocking = true sets, and throws InvalidOperationException when the flag is off: ImGui only accepts that flag before the first frame, so the pump cannot turn it on itself, and Hexa's dockspace would silently do nothing without it. Showing a dialog before either pump has ever run throws InvalidOperationException, as does calling Show() on a dialog instance that is already shown (Hexa would register the same instance twice and permanently block input) — wait for the close callback, or create a new instance per showing. A pump is not needed just to keep animated widgets like ToggleSwitch correct — it self-ticks when unpumped — only to show dialogs or docked windows.
Callback-driven Editors
Sequencer and the multi-curve CurveEditor overload take a source object they interrogate while drawing, instead of a value:
- Subclass
SequenceSourcefor a timeline:FrameMin,FrameMax,ItemCount,GetItem(int), andSetItemRange(int index, int start, int endFrame), which receives drag edits. - Subclass
CurveSourcefor a multi-curve graph:CurveCount,ViewMin,ViewMax,GetPointCount(int),GetPoints(int),GetCurveColor(int),EditPoint(int, int, Vector2),AddPoint(int, Vector2).
Neither needs a deferred-drawing pump — both are immediate-mode calls that happen to take a callback object, and neither Sequencer nor CurveEditor calls DrawDeferred()/DrawDeferredDocked().
public static bool ImGuiWidgets.Sequencer(SequenceSource source, ref int currentFrame, ref bool expanded,
ref int selectedEntry, ref int firstFrame, SequencerFeatures features = SequencerFeatures.EditAll);
public static bool ImGuiWidgets.CurveEditor(CurveSource source, Vector2 size, string id);
CurveEditor also has a single-curve overload taking a CurveData value instead of a CurveSource:
public static bool ImGuiWidgets.CurveEditor(CurveData curve, Vector2 size, Vector2 rangeMin,
Vector2 rangeMax, ref int selection, string label);
CurveData wraps the curve representation the widget expects — points are CurveKnot (Position plus a CurvePointKind of .Smooth or .Corner), shaped by CurveShape.Smooth/.Freehand — and tracks a dirty flag so Sample(float t) recomputes its cache automatically after AddPoint/SetPoint/RemovePoint/Clear, a Shape change, or an edit made through the widget.
BezierEditor edits a BezierControlPoints pair (First/Second) directly, with no source object:
public static bool ImGuiWidgets.BezierEditor(string label, ref BezierControlPoints points, float size = 128f);
Acknowledgments
ImGuiWidgets is built on:
- Dear ImGui - The immediate mode GUI library these widgets draw into
- Hexa.NET.ImGui - The .NET bindings for Dear ImGui
- Hexa.NET.ImGui.Widgets - The upstream widget collection behind the Hexa-backed widgets, dialogs and editors here
- Hexa.NET.Math - The math types those widgets marshal through
- ktsu.Semantics -
Color, path and string types used across the widget surface - ktsu.TextFilter - Glob, regex and fuzzy filtering behind
SearchBox - ktsu.Extensions - Collection extension methods
- ktsu.ScopedAction - The RAII scope type behind
ScopedId,ScopedDisableandTree
and inspired by the following projects:
Contributing
Contributions are welcome! For feature requests, bug reports, or questions, please open an issue on the GitHub repository. If you would like to contribute code, please open a pull request with your changes.
License
ImGui.Widgets is licensed under the MIT License. See LICENSE.md for more information.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Hexa.NET.ImGui (>= 2.2.9)
- Hexa.NET.ImGui.Widgets (>= 1.2.18)
- Hexa.NET.Math (>= 2.0.8)
- ktsu.Extensions (>= 1.9.3)
- ktsu.ImGui.Color (>= 3.80.0)
- ktsu.ImGui.Probes (>= 3.80.0)
- ktsu.ImGui.Rendering (>= 3.80.0)
- ktsu.ImGui.Styler (>= 3.80.0)
- ktsu.Keybinding (>= 2.1.7)
- ktsu.ScopedAction (>= 1.1.46)
- ktsu.Semantics.Color (>= 5.12.1)
- ktsu.Semantics.Paths (>= 5.12.1)
- ktsu.Semantics.Strings (>= 5.12.1)
- ktsu.TextFilter (>= 1.7.13)
-
net8.0
- Hexa.NET.ImGui (>= 2.2.9)
- Hexa.NET.ImGui.Widgets (>= 1.2.18)
- Hexa.NET.Math (>= 2.0.8)
- ktsu.Extensions (>= 1.9.3)
- ktsu.ImGui.Color (>= 3.80.0)
- ktsu.ImGui.Probes (>= 3.80.0)
- ktsu.ImGui.Rendering (>= 3.80.0)
- ktsu.ImGui.Styler (>= 3.80.0)
- ktsu.Keybinding (>= 2.1.7)
- ktsu.ScopedAction (>= 1.1.46)
- ktsu.Semantics.Color (>= 5.12.1)
- ktsu.Semantics.Paths (>= 5.12.1)
- ktsu.Semantics.Strings (>= 5.12.1)
- ktsu.TextFilter (>= 1.7.13)
-
net9.0
- Hexa.NET.ImGui (>= 2.2.9)
- Hexa.NET.ImGui.Widgets (>= 1.2.18)
- Hexa.NET.Math (>= 2.0.8)
- ktsu.Extensions (>= 1.9.3)
- ktsu.ImGui.Color (>= 3.80.0)
- ktsu.ImGui.Probes (>= 3.80.0)
- ktsu.ImGui.Rendering (>= 3.80.0)
- ktsu.ImGui.Styler (>= 3.80.0)
- ktsu.Keybinding (>= 2.1.7)
- ktsu.ScopedAction (>= 1.1.46)
- ktsu.Semantics.Color (>= 5.12.1)
- ktsu.Semantics.Paths (>= 5.12.1)
- ktsu.Semantics.Strings (>= 5.12.1)
- ktsu.TextFilter (>= 1.7.13)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on ktsu.ImGui.Widgets:
| Package | Downloads |
|---|---|
|
ktsu.ImGui.NodeEditor
A visual node editor for Dear ImGui built on ImNodes, with the graph kept away from the drawing: the engine owns nodes, links and layout and knows nothing about ImGui, while the renderer draws what it holds and the input handler turns interactions into requests the engine can accept or refuse. Nodes can be declared as ordinary types decorated with ktsu.NodeGraph attributes and instantiated by reflection, with connections checked against the rules that metadata declares. Optional force-directed layout settles the graph, and the view zooms from quarter to double scale. Every edit can be undone through a ktsu.UndoRedo history, keyboard commands follow a ktsu.Keybinding keymap, dragged nodes can snap to the grid, and labelled comment boxes group regions of the graph and carry their nodes when moved. |
|
|
ktsu.Coder.Graph
A flexible and extensible .NET library for representing code as language-agnostic Abstract Syntax Trees, serializing them to human-readable YAML for round-trip storage and version control, and generating source in C#, Python, JavaScript and C++. Provides strongly-typed AST nodes for classes, functions, parameters, statements, expressions and typed literals, with a plugin-based architecture for adding target languages, full deep-cloning support and custom metadata on any node. Ships an ImGui node-graph editor over the same AST, with a force-directed layout, an inspector for every node's properties, undo/redo, and a desktop application built on it. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.80.1-pre.1 | 57 | 11/17/2026 |
| 3.80.0 | 652 | 11/10/2026 |
| 3.79.1-pre.3 | 84 | 10/28/2026 |
| 3.79.1-pre.2 | 82 | 10/27/2026 |
| 3.79.1-pre.1 | 83 | 10/26/2026 |
| 3.79.0 | 606 | 10/26/2026 |
| 3.78.3 | 195 | 10/25/2026 |
| 3.78.2 | 297 | 10/24/2026 |
| 3.78.1 | 158 | 10/24/2026 |
| 3.78.0 | 216 | 10/22/2026 |
| 3.77.3 | 208 | 10/21/2026 |
| 3.77.2 | 177 | 10/21/2026 |
| 3.77.1 | 191 | 10/21/2026 |
| 3.77.0 | 169 | 10/20/2026 |
| 3.76.1 | 184 | 10/20/2026 |
| 3.76.0 | 160 | 10/20/2026 |
| 3.75.4 | 809 | 10/19/2026 |
| 3.75.3 | 674 | 10/18/2026 |
| 3.75.2 | 219 | 10/17/2026 |
| 3.75.2-pre.1 | 85 | 10/16/2026 |
## v3.80.0 (minor)
Changes since v3.79.0:
- Add a SessionStart hook for Claude Code cloud sessions (#713) (matt-edmondson)
- Use Path.Join for the temporary PNG path in PngEncoderTests (Claude)
- [minor] Move image decoding into ktsu.Imaging (Claude)
- Read C++ raw string literals as one string [minor] (#742) (matt-edmondson)
- Read HTML script and style bodies as text up to their closing tag [minor] (#741) (matt-edmondson)
- Keep a backslashed quote inside a Python raw string [minor] (#740) (matt-edmondson)