如何将绿色框中的“ hello and test”字符串的位置更改为图像的中心位置?我想将hello字符串和测试的位置放在图像(标记为红色圆圈)的中间,图像的链接> https://cdn.pbrd.co/images/I1hTWNS.png
我添加了“中心”对齐方式,但是字符串的位置仍然在图像的左侧。
public void drawString()
{
string firstText = "Hello" + Environment.NewLine + "Test";
string imageFilePath = directory + name + "\\Desktop\\plain.jpg";
Bitmap newBitmap;
using (var bitmap = (Bitmap)Image.FromFile(imageFilePath))//load the image file
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
using (Font arialFont = new Font("Arial", 26, FontStyle.Bold, GraphicsUnit.Point))
{
Rectangle rect = new Rectangle(0, 0, ClientSize.Width - 10, ClientSize.Height - 10);
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
graphics.DrawString(firstText, arialFont, Brushes.Red, rect, sf);
graphics.DrawRectangle(Pens.Green, rect);
}
}
newBitmap = new Bitmap(bitmap);
}
newBitmap.Save(imageFilePath);//save the image file
newBitmap.Dispose();
}
我添加了“中心”对齐方式,但是字符串的位置仍然在图像的左侧。
答案 0 :(得分:2)
您的文本确实在创建的矩形中居中。问题是矩形是基于ClientSize
Height
和Width
的矩形,它们来自内部控件。
您要使用的是Bitmap
和Height
的当前Width
属性。
而不是:
Rectangle rect = new Rectangle(0, 0, ClientSize.Width - 10, ClientSize.Height - 10);
您想要的:
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);