文字列描写時の大きさを取得する
C#で文字をイメージとして描写するときの「文字の画像」のサイズを取得する方法を紹介
イメージ内の文字列の改行で結構使ったので,忘れないうちにメモ書きc⌒っ゚д゚)っφ メモメモ...
using System.Drawing; //←「参照の追加」,usingの追加必要 /// <summary> /// 描写時の文字列の画像の幅を返します /// </summary> /// <param name="str">描写する文字列</param> /// <returns>描写する文字列の幅</returns> private double fontSize(string str) { //文字サイズの計算のための描写先イメージ作成(大きさ適当) Bitmap testBitmap = new Bitmap(300,300); Graphics g = Graphics.FromImage(testBitmap); string setFontStyle = "MS 明朝" int pxFontSize = 30; SizeF size = g.MeasureString(str,new Font(setFontStyle,pxfontSize)); double width; //, height; width = size.Width; //構造体の数値はdouble型 //height = size.Height; //高さを取得したいとき testBitmap.Dispose(); g.Dispose(); return width; }
このプログラムを改行で使ってるうちに気になったことが一つ
ある文字列をそのまま描写したときと,分割したときの描写したとき,サイズって変化するのか・・・
なので以下のコードを書いて確認してみました.ご参考にどうぞ
using System; using System.Drawing; namespace 文字列描写サイズ分割テスト { class Program { static void Main(string[] args) { string str; str = "0123456789abcdef"; //この文字で比較 string[] cutString = new string[2]; //分割文字記録用 int i = 10; //文字列分割場所指定 int count; count = str.Length; //文字列の長さを取得 cutString[0] = str.Substring(0, i); cutString[1] = str.Substring(i, count - i); Console.WriteLine("編集前文字列 :{0}", str); Console.WriteLine("編集文字列その1:{0}", cutString[0]); Console.WriteLine("編集文字列その2:{0}\n", cutString[1]); //文字列の描写サイズ(幅)を取得 double[] size = new double[3]; size[0] = imgFontSize(str); size[1] = imgFontSize(cutString[0]); size[2] = imgFontSize(cutString[1]); Console.WriteLine("編集前文字列 幅 :{0}", size[0]); Console.WriteLine("編集文字列その1 幅:{0}", size[1]); Console.WriteLine("編集文字列その2 幅:{0}", size[2]); Console.WriteLine("編集文字列幅の合計 :{0}", size[1] + size[2]); Console.Read(); return; } //文字列描写時のサイズ計算 private static double imgFontSize(string str) { Bitmap testBitmap = new Bitmap(300, 300); Graphics g = Graphics.FromImage(testBitmap); SizeF size = g.MeasureString(str, new Font("MS 明朝", 30)); testBitmap.Dispose(); g.Dispose(); return size.Width; //幅が戻り値 } } }
↓結果
編集前文字列 :0123456789abcdef
編集文字列その1:0123456789
編集文字列その2:abcdef
編集前文字列 幅 :343.333251953125
編集文字列その1 幅:219.583297729492
編集文字列その2 幅:137.083312988281
編集文字列幅の合計 :356.666610717773