Skip to content

Commit a1a1767

Browse files
committed
Split off GetTextDimensions()
So it is much more convenient to find the width of a text without actually allocating the rectangle in the GUI.
1 parent d430d1b commit a1a1767

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

Yafc.UI/ImGui/ImGuiBuilding.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,19 @@ public void BuildText(string? text, Font? font = null, bool wrap = false, RectAl
100100
}
101101
}
102102

103+
public Vector2 GetTextDimensions(out TextCache? cache, string? text, Font? font = null, bool wrap = false, float maxWidth = float.MaxValue) {
104+
if (string.IsNullOrEmpty(text)) {
105+
cache = null;
106+
return Vector2.Zero;
107+
}
108+
109+
var fontSize = GetFontSize(font);
110+
cache = textCache.GetCached((fontSize, text, wrap ? (uint)UnitsToPixels(MathF.Max(width, 5f)) : uint.MaxValue));
111+
float textWidth = Math.Min(cache.texRect.w / pixelsPerUnit, maxWidth);
112+
113+
return new Vector2(textWidth, cache.texRect.h / pixelsPerUnit);
114+
}
115+
103116
public Rect AllocateTextRect(out TextCache? cache, string? text, Font? font = null, bool wrap = false, RectAlignment align = RectAlignment.MiddleLeft, float topOffset = 0f, float maxWidth = float.MaxValue) {
104117
var fontSize = GetFontSize(font);
105118
Rect rect;
@@ -108,9 +121,8 @@ public Rect AllocateTextRect(out TextCache? cache, string? text, Font? font = nu
108121
rect = AllocateRect(0f, topOffset + (fontSize.lineSize / pixelsPerUnit));
109122
}
110123
else {
111-
cache = textCache.GetCached((fontSize, text, wrap ? (uint)UnitsToPixels(MathF.Max(width, 5f)) : uint.MaxValue));
112-
float textWidth = Math.Min(cache.texRect.w / pixelsPerUnit, maxWidth);
113-
rect = AllocateRect(textWidth, topOffset + (cache.texRect.h / pixelsPerUnit), align);
124+
Vector2 textSize = GetTextDimensions(out cache, text, font, wrap, maxWidth);
125+
rect = AllocateRect(textSize.X, topOffset + (textSize.Y), align);
114126
}
115127

116128
if (topOffset != 0f) {

0 commit comments

Comments
 (0)