Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit cc3d462

Browse files
committed
adds MeasureString to calculate the size of a string before rendering
1 parent f1673d6 commit cc3d462

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

source/GameOverlay/Drawing/Graphics.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1255,6 +1255,43 @@ public void DrawTextWithBackground(Font font, float fontSize, IBrush brush, IBru
12551255
layout.Dispose();
12561256
}
12571257

1258+
/// <summary>
1259+
/// Measures the specified string when drawn with the specified Font.
1260+
/// </summary>
1261+
/// <param name="font">Font that defines the text format of the string.</param>
1262+
/// <param name="fontSize">The size of the Font. (does not need to be the same as in Font.FontSize)</param>
1263+
/// <param name="text">String to measure.</param>
1264+
/// <returns>This method returns a Point containing the width (x) and height (y) of the given text.</returns>
1265+
public Point MeasureString(Font font, float fontSize, string text)
1266+
{
1267+
if (!IsDrawing) throw ThrowHelper.UseBeginScene();
1268+
1269+
if (text == null) throw new ArgumentNullException(nameof(text));
1270+
if (text.Length == 0) return default;
1271+
1272+
var layout = new TextLayout(_fontFactory, text, font.TextFormat, Width, Height);
1273+
1274+
if (fontSize != font.FontSize)
1275+
{
1276+
layout.SetFontSize(fontSize, new TextRange(0, text.Length));
1277+
}
1278+
1279+
var result = new Point(layout.Metrics.Width, layout.Metrics.Height);
1280+
1281+
layout.Dispose();
1282+
1283+
return result;
1284+
}
1285+
1286+
/// <summary>
1287+
/// Measures the specified string when drawn with the specified Font.
1288+
/// </summary>
1289+
/// <param name="font">Font that defines the text format of the string.</param>
1290+
/// <param name="text">String to measure.</param>
1291+
/// <returns>This method returns a Point containing the width (x) and height (y) of the given text.</returns>
1292+
public Point MeasureString(Font font, string text)
1293+
=> MeasureString(font, font.FontSize, text);
1294+
12581295
/// <summary>
12591296
/// Draws a string with a background box in behind using the given font, size and position.
12601297
/// </summary>

0 commit comments

Comments
 (0)