Question

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.

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top