Horizontal Slider with Labels

Hi,

I was just wondering if there is a simple way to label a GUILayout horizontal slider dynamically as such (shown in the image below):

24579-screenshot.png

I want the ‘100’ to appear at the right end of the slider and I want it to be dynamic so that whenever I resize the whole menu, the ‘100’ remains at the desired position.

I’m coding in C#.


Thank you in advance for your help.

You could try changing the text alignment of the second label to be UpperRight rather than Left, something like:

var progress : float = 50;
var min : float = 0;
var max : float = 100;

function OnGUI(){
	GUILayout.BeginArea(Rect(10, 10, 200, 100));
	progress = GUILayout.HorizontalSlider(progress, min, max);
		GUILayout.BeginHorizontal();
			var defaultAlignment = GUI.skin.label.alignment;
			GUILayout.Label(min.ToString());
			GUI.skin.label.alignment = TextAnchor.UpperRight;
			GUILayout.Label(max.ToString());
			GUI.skin.label.alignment = defaultAlignment;
		GUILayout.EndHorizontal();
	GUILayout.EndArea();
}

Scribe

Using EditorGUI instead of GUILayout, Scribe’s solution didn’t work for me as such. I made it through tweaking it that way :

116490-slider.jpg

Rect position = EditorGUILayout.GetControlRect (false, 2*EditorGUIUtility.singleLineHeight); // Get two lines for the control
position.height *= 0.5f;
tgt.FitOrFill = EditorGUI.Slider (position,"Fit or Fill", tgt.FitOrFill, 0, 1);

// Set the rect for the sub-labels
position.y	 += position.height;
position.x	 += EditorGUIUtility.labelWidth;
position.width -= EditorGUIUtility.labelWidth + 54; //54 seems to be the width of the slider's float field

//sub-labels
GUIStyle style = GUI.skin.label;
style.alignment = TextAnchor.UpperLeft;  EditorGUI.LabelField (position, "Fit",  style);
style.alignment = TextAnchor.UpperRight; EditorGUI.LabelField (position, "Fill", style);

Just cleaning up a bit more.

SerializedProperty bitRateFactor = property.FindPropertyRelative("m_bitRateFactor");

position = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight);

// Draw label
position = EditorGUI.PrefixLabel(position, new GUIContent("Bitrate Factor"));
EditorGUI.indentLevel--;

// Draw slider
bitRateFactor.floatValue = EditorGUI.Slider(position, bitRateFactor.floatValue, 0f, 1f);
float labelWidth = position.width;

// Move to next line
position.y          += EditorGUIUtility.singleLineHeight;

// Subtract the text field width thats drawn with slider
position.width      -= EditorGUIUtility.fieldWidth;

GUIStyle style = GUI.skin.label;
TextAnchor defaultAlignment = GUI.skin.label.alignment;
style.alignment = TextAnchor.UpperLeft; EditorGUI.LabelField(position, "Low Bitrate", style);
style.alignment = TextAnchor.UpperRight; EditorGUI.LabelField(position, "High Bitrate", style);
GUI.skin.label.alignment = defaultAlignment;

And here is how it looks -
129580-sliderwithlabels.png