문제

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.

도움이 되었습니까?

해결책

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top