Horizontal Slider with Labels


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


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);
			var defaultAlignment = GUI.skin.label.alignment;
			GUI.skin.label.alignment = TextAnchor.UpperRight;
			GUI.skin.label.alignment = defaultAlignment;


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


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

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"));

// 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 -