Tuesday, 12 April 2016

Generate Bitmap containing Centered Text

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication14
{
    class Program
    {
        static void Main(string[] args)
        {
            string txt = "HELLO";
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(131, 50);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
            g.Clear(System.Drawing.Color.DarkGreen);
            System.Drawing.Font f = new System.Drawing.Font("Courier", 25, System.Drawing.FontStyle.Bold);
            System.Drawing.SizeF szf = new System.Drawing.SizeF();
            szf = g.MeasureString(txt, f);
            int xoff = (int)((bmp.Width - szf.Width) / 2);
            g.DrawString(txt, f, System.Drawing.Brushes.Red, new System.Drawing.Rectangle(/*x*/xoff, /*y*/0, bmp.Width, bmp.Height));
            bmp.Save("c:/temp/xxx.bmp");
        }
    }

}

No comments:

Post a Comment