Advertisement
NPSF3000

String To Image [Chess Icons]

Apr 15th, 2013
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. //  You know you're a programmer when this is how
  2. //  You get some cheap chess icons...
  3.  
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6.  
  7. namespace StringToImage
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             for (int i = 0; i < 12; i++)
  14.                 TextToImage(((char)('\u2654' + i)).ToString(), 256, 256, i > 5 ? Color.Black : Color.White)
  15.                             .Save("C:\\CHESS\\" + "WB"[i / 6] + "KQRBNP"[i % 6] + ".png", ImageFormat.Png);
  16.         }
  17.  
  18.         public static Bitmap TextToImage(string text, int height = 40, int width = 150, Color? textColor = null)
  19.         {
  20.             textColor = textColor ?? Color.White;
  21.  
  22.             Bitmap bmp = new Bitmap(width, height);
  23.             using (Graphics gr = Graphics.FromImage(bmp))
  24.             {
  25.                 gr.FillRectangle(new SolidBrush(Color.Transparent), 0, 0, width, height);
  26.  
  27.                 Font fn = new Font("Copperplate Gothic", 1, FontStyle.Regular);//"Comic Sans MS"
  28.                 for (int fnSize = 1; !string.IsNullOrWhiteSpace(text); fnSize++)
  29.                 {
  30.                     var newFn = new Font(fn.FontFamily, fnSize, fn.Style);
  31.                     var size = gr.MeasureString(text.Replace(' ', '_'), newFn);
  32.                     if (size.Height < height && size.Width < width) fn = newFn;
  33.                     else break;
  34.                 }
  35.  
  36.                 var offset = bmp.Size - gr.MeasureString(text.Replace(' ', '_'), fn);
  37.                 gr.DrawString(text, fn, new SolidBrush(textColor.Value), offset.Width / 2, offset.Height / 2);
  38.                 return bmp;
  39.             }
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement