在图像上写入文本(指定宽度)

Kis*_*jar 3 .net c# system.drawing drawstring

当前示例

我正在为员工生成 ICard。我必须在 ICard 上写下雇员的地址。

            Image blankICard = Image.FromFile(@"C:\Users\admin\Pictures\filename.jpg");

            Bitmap outputImage = new Bitmap(blankICard.Width, blankICard.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.SolidBrush b = new SolidBrush(Color.FromArgb(255, 88, 89, 91));
            using (Graphics graphics = Graphics.FromImage(outputImage))
            {
                graphics.DrawImage(blankICard, new Rectangle(0, 0, blankICard.Width, blankICard.Height),
                new Rectangle(new Point(), blankICard.Size), GraphicsUnit.Pixel);

                Font stringFont = new Font("FreightSans Medium", 20, FontStyle.Regular);

                string address = "Address goes here";

                graphics.DrawString(address, new Font("FreightSans Medium", 20, FontStyle.Regular), b, new Point(621, 234));
                graphics.DrawString("Employee Code:12345678", new Font("FreightSans Medium", 26, FontStyle.Regular), b, new Point(350, 407));
            }
Run Code Online (Sandbox Code Playgroud)

电流输出显示在图像的左侧。这是我的字符串开箱即用会发生什么。

我想把它装在固定尺寸的盒子里。

示例显示在图像的右侧。

Sil*_*ind 5

使用Graphics.DrawString需要Rectangle而不是点的重载。这样您就可以将文本换行以适应指定的宽度。

using (Graphics graphics = Graphics.FromImage(outputImage)){
  // Draw whatever you need first
  // ....
  // Create font...
  graphics.DrawString(employeeCode, font, Brushes.Black,
                       new Rectangle(0, 25, maxWidth, maxHeight);
}
Run Code Online (Sandbox Code Playgroud)

就那么简单 :)