Hi there,
I made this simple method to get clipping text with dots, it works great, but I feel like there has to be a better way in achieving this. I’m afraid it might become heavy on performance, if many elements (labels) are drawn that runs this function.
P.S. This is for EditorWindow script.
Does anyone have any tips on how could I improve this? Thank you
private void OnGUI()
{
//Example usage..
Rect labelRect = new Rect(rect.x + 5, rect.y + rect.height, rect.width - 10, 20);
GUIStyle labelStyle = new GUIStyle(EditorStyles.label)
{
alignment = TextAnchor.MiddleLeft,
clipping = TextClipping.Clip,
wordWrap = false
};
GUI.Label(labelRect, Shortcut_Util.GetClippingText(obj.name, labelRect), labelStyle);
}
const string ellipsis = "...";
public static string GetClippingText(string text, Rect area)
{
if (GUI.skin.label.CalcSize(new GUIContent(text)).x > area.width)
{
var clippedText = ellipsis;
var characters = text.ToCharArray();
for (int i = 0; i < characters.Length; i++)
{
clippedText = clippedText.Insert(i, characters[i].ToString());
if (GUI.skin.label.CalcSize(new GUIContent(clippedText)).x >= area.width)
{
break;
}
}
return clippedText;
}
return text;
}