visual-studio 如何在 TrackBar 中使用浮动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2114485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use floats with TrackBar
提问by rross
I'm using a TrackBarcontrol. 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 TrackBarcontrol to accept floats?
我正在使用TrackBar控件。默认情况下,其值为int32。我真的很想使用十进制值,以便用户可以在更细粒度的级别进行选择。我怎样才能TrackBar控制接受浮点数?
回答by Reed Copsey
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.
您可以使用乘数。举例来说,您想让 TrackBar 控件从 0 - 5 以 0.01 的增量变化。只需将最小值设置为 0,最大值设置为 500,然后增加 1。
When you go to set your float value, multiply it by 100, and use that for the TrackBar value.
当您要设置浮点值时,将其乘以 100,然后将其用于 TrackBar 值。
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.
您应该能够以这种方式获得任何(现实的)精度,因为 TrackBar 使用整数,并且具有可用的 Int32 的完整数据范围。这比用户界面要求的精度高得多。
回答by Bitterblue
Another idea would be to inheritfrom TrackBarand simulate float values in a custom class in the way Reed Copsey suggested to use ints and multiply with a precision factor.
另一个想法是继承自TrackBar和模拟浮点值在方式里德·科普塞建议使用整数乘法和用精密因子的自定义类。
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); } }
}

