Created
March 23, 2018 06:13
-
-
Save mjs3339/8a956e9927e1366df48c9ff50aae65dd to your computer and use it in GitHub Desktop.
C# TextFontGraphics Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class TextFontGraphics | |
{ | |
public static int GetNumberOfLines(this string text) | |
{ | |
return text.Split('\n').Length; | |
} | |
public static int GetTextCharacterCount(this string text) | |
{ | |
return text.Count(c => c != '\r' && c != '\n'); | |
} | |
public static Size MeasureText(this string text, Font font, int addwidth = 0, int addheight = 0) | |
{ | |
if (string.IsNullOrEmpty(text)) return Size.Empty; | |
var mh = text.GetMinimumTextBoxHeight(font); | |
var mw = text.GetMinimumTextBoxWidth(font); | |
var fs = font.GetFontSize(); | |
var Height = mh + (int) fs.Height * addheight; | |
var Width = mw + (int) fs.Width * addwidth; | |
return new Size((int) Width, (int) Height); | |
} | |
public static SizeF GetFontSize(this Font f) | |
{ | |
if (f == null) return SizeF.Empty; | |
Image fakeImage = new Bitmap(1, 1); | |
var graphics = Graphics.FromImage(fakeImage); | |
var size = graphics.MeasureString("Ag", f); | |
var ns = new SizeF(); | |
ns.Height = size.Height; | |
ns.Width = size.Width / 2; | |
return ns; | |
} | |
public static SizeF GetFontSize(this Font f, string l) | |
{ | |
if (f == null) return SizeF.Empty; | |
if (string.IsNullOrEmpty(l)) return Size.Empty; | |
Image fakeImage = new Bitmap(1, 1); | |
var graphics = Graphics.FromImage(fakeImage); | |
var size = graphics.MeasureString(l, f); | |
var ns = new SizeF(); | |
ns.Height = size.Height; | |
ns.Width = size.Width; | |
return ns; | |
} | |
public static float GetMinimumTextBoxHeight(this string text, Font font) | |
{ | |
if (font == null) return 0; | |
if (string.IsNullOrEmpty(text)) return 0; | |
var lineCount = text.Split('\n').Length; | |
var fs = font.GetFontSize(); | |
var MinimumSize = lineCount * 1.15f * fs.Height; | |
return MinimumSize; | |
} | |
public static float GetMinimumTextBoxWidth(this string text, Font font) | |
{ | |
if (font == null) return 0; | |
if (string.IsNullOrEmpty(text)) return 0; | |
var lines = text.Split('\n'); | |
var MaxFontLength = 0; | |
foreach (var l in lines) | |
{ | |
var fs = (int) Math.Ceiling(font.GetFontSize(l).Width); | |
if (fs > MaxFontLength) MaxFontLength = fs; | |
} | |
return MaxFontLength; | |
} | |
[STAThread] | |
public static SizeF GetCurrentScreenSize() | |
{ | |
var f = new Window(); | |
var helper = new WindowInteropHelper(f); | |
var currentScreen = Screen.FromHandle(helper.Handle); | |
var s = currentScreen.Bounds.Size; | |
return s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment