Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use floats with TrackBar

I'm using a TrackBar control. By default its values are int32. I would really like to use decimal values so the use can select at a more granular level. How can I get the TrackBar control to accept floats?

like image 217
rross Avatar asked Jan 22 '10 02:01

rross


2 Answers

You can use a multiplier. Say, for example, you wanted to make your TrackBar control go from 0 - 5 with 0.01 increments. Just set the Minimum to 0, the Maximum to 500, and increment by 1.

When you go to set your float value, multiply it by 100, and use that for the TrackBar value.

You should be able to get any (realistic) degree of precision in this manner, since the TrackBar works with ints, and has the full data range of Int32 available. This is much more precision than a user interface requires.

like image 79
Reed Copsey Avatar answered Oct 15 '22 18:10

Reed Copsey


Another idea would be to inherit from TrackBar and simulate float values in a custom class in the way Reed Copsey suggested to use ints and multiply with a precision factor.

The following works pretty neat for small float values:

class FloatTrackBar: TrackBar
{
    private float precision = 0.01f;

    public float Precision
    {
        get { return precision; }
        set
        {
            precision = value;
            // todo: update the 5 properties below
        }
    }
    public new float LargeChange
    { get { return base.LargeChange * precision; } set { base.LargeChange = (int) (value / precision); } }
    public new float Maximum
    { get { return base.Maximum * precision; } set { base.Maximum = (int) (value / precision); } }
    public new float Minimum
    { get { return base.Minimum * precision; } set { base.Minimum = (int) (value / precision); } }
    public new float SmallChange
    { get { return base.SmallChange * precision; } set { base.SmallChange = (int) (value / precision); } }
    public new float Value
    { get { return base.Value * precision; } set { base.Value = (int) (value / precision); } }
}
like image 38
Bitterblue Avatar answered Oct 15 '22 20:10

Bitterblue