Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw centered text onto a jpg using system.drawing in c#

I am using the following code to draw text onto a jpg image but it requires x/y coordinate percision on where to place the text.

var bmp = new Bitmap("C:\\testing\\Given.jpg");
var gra = Graphics.FromImage(bmp);

var text = "The Berman's";
var font = new Font("Segoe Script", 24);
var brush = Brushes.Orange;
var point = new PointF(130, 224);

gra.DrawString(text, font, brush, point);
bmp.Save("C:\\testing\\Custom.jpg");

How would I go about centering text onto an image? I am guessing it would have to do with defining some sort of container (rectangle maybe?) that is the width of the image and centering the text within that? Not sure what the best practice would be for this.

like image 362
Brian David Berman Avatar asked Oct 11 '10 18:10

Brian David Berman


1 Answers

using(var sf = new StringFormat()
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center,
})
{
    gra.DrawString(text, font, brush, new Rectangle(0, 0, bmp.Width, bmp.Height), sf);
}
like image 79
max Avatar answered Oct 05 '22 06:10

max