Skip to content

Instantly share code, notes, and snippets.

@zaafar
Created December 25, 2020 06:56
Show Gist options
  • Save zaafar/ccf2c32a9fa4d85cbe0dcd7163beb81d to your computer and use it in GitHub Desktop.
Save zaafar/ccf2c32a9fa4d85cbe0dcd7163beb81d to your computer and use it in GitHub Desktop.
Potential Solution
public static Vector2 CalcTextSize(string text)
=> CalcTextSizeImpl(text.AsSpan());
public static Vector2 CalcTextSize(string text, int start)
=> CalcTextSizeImpl(text.AsSpan(start));
public static Vector2 CalcTextSize(string text, float wrapWidth)
=> CalcTextSizeImpl(text.AsSpan(), wrapWidth: wrapWidth);
public static Vector2 CalcTextSize(string text, bool hideTextAfterDoubleHash)
=> CalcTextSizeImpl(text.AsSpan(), hideTextAfterDoubleHash: hideTextAfterDoubleHash);
public static Vector2 CalcTextSize(string text, int start, int length)
=> CalcTextSizeImpl(text.AsSpan(start, length));
public static Vector2 CalcTextSize(string text, int start, bool hideTextAfterDoubleHash)
=> CalcTextSizeImpl(text.AsSpan(start), hideTextAfterDoubleHash: hideTextAfterDoubleHash);
public static Vector2 CalcTextSize(string text, int start, float wrapWidth)
=> CalcTextSizeImpl(text.AsSpan(start), wrapWidth: wrapWidth);
public static Vector2 CalcTextSize(string text, bool hideTextAfterDoubleHash, float wrapWidth)
=> CalcTextSizeImpl(text.AsSpan(), hideTextAfterDoubleHash: hideTextAfterDoubleHash, wrapWidth: wrapWidth);
public static Vector2 CalcTextSize(string text, int start, int length, bool hideTextAfterDoubleHash)
=> CalcTextSizeImpl(text.AsSpan(start, length), hideTextAfterDoubleHash);
public static Vector2 CalcTextSize(string text, int start, int length, float wrapWidth)
=> CalcTextSizeImpl(text.AsSpan(start, length), wrapWidth: wrapWidth);
public static Vector2 CalcTextSize(string text, int start, int length, bool hideTextAfterDoubleHash, float wrapWidth)
=> CalcTextSizeImpl(text.AsSpan(start, length), hideTextAfterDoubleHash, wrapWidth);
private static Vector2 CalcTextSizeImpl(
ReadOnlySpan<char> text,
bool hideTextAfterDoubleHash = false,
float wrapWidth = -1.0f)
{
Vector2 ret;
byte* nativeTextStart = null;
byte* nativeTextEnd = null;
int textByteCount = 0;
if (text != null)
{
textByteCount = Encoding.UTF8.GetByteCount(text);
if (textByteCount > Util.StackAllocationSizeLimit)
{
nativeTextStart = Util.Allocate(textByteCount + 1);
}
else
{
byte* nativeTextStackBytes = stackalloc byte[textByteCount + 1];
nativeTextStart = nativeTextStackBytes;
}
int nativeTextOffset = Util.GetUtf8(text, nativeTextStart, textByteCount);
nativeTextStart[nativeTextOffset] = 0;
nativeTextEnd = nativeTextStart + nativeTextOffset;
}
ImGuiNative.igCalcTextSize(&ret, nativeTextStart, nativeTextEnd, *((byte*)(&hideTextAfterDoubleHash)), wrapWidth);
if (textByteCount > Util.StackAllocationSizeLimit)
{
Util.Free(nativeTextStart);
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment