Last time we’ve made a small IMGUI framework, now we are going to add scrollbars, or sliders if you prefer that term, to our set of controls. Sliders work a bit differently than buttons because you’ll have to know last time’s value to show the slider correctly, and we can’t store state for each slider in the IMGUI itself (or well, that goes against the idea).
Without further ado (and because I’m pretty busy lately) I’ll put the source code for a scrollbar here, and afterwards explain the method.
As you can see a scrollbar is a bit more complicated than a button, but the code is still pretty short. I think the code is pretty self explanatory, but I’ll add a short overview of the steps here:
A scrollbar is called with as parameter a float called value, this value indicates where on the scrollbar the grip should be (between 0 and max)
First trim value so that it is between 0 and max
Determine if the mouse is over the scrollbar, and if so check if the mouse is being pressed
Draw our scrollbar background in the right color
Now calculate where our grip should be positioned and how big it should be (two code paths, one for horizontal and one for vertical)
If we have a scrollbar background of 60x500 we want our grip to be of size 60x60, and vice-versa
If we have a value near max we want the grip to be more to the right (or top) and vice-versa
Now draw our grip
Last, if the scrollbar is the activeItem, we need to check if the mouse (and thus the grip) was moved (again two code paths).
This is slightly tricky so take a good look at that code.
In the end, return the value (which was changed if the grip was moved).
Well, now we have that nice scrollbar, how are we going to use it?
(Note the call to imgui.Update(…) which I might have forgotten last time (oops).
Easy isn’t it? A simmilar technique is used for text input, but you’d need an extra state to keep track of the item the mouse last clicked that receives keyboard input, I’ll go over that next time. I would add a nice picture here to show you how this all looks, but tbh my programmer art is so ugly that I’m scared it would frighten you away from using this technique.