[英]How to get contents in graphics.Drawstring in new line of c#
您好,我正在收据打印机上打印文本,我必须在上面打印产品名称,但是产品名称在“数量”字段上被覆盖,我可以使用特定代码在特定长度后在新行中获取该名称字符串吗? 第3列具有产品名称,如(杏仁Kesar Kanti身体清洁剂)如何在换行中获取此文本并管理发票的空间。
while (i < dataGridView2.Rows.Count)
{
if (height > e.MarginBounds.Height)
{
height = 500;
width = 500;
//e.HasMorePages = true;
return;
}
//height += dataGridView1.Rows[i].Height;
// e.Graphics.DrawRectangle(Pens.Black, 20, height, dataGridView1.Columns[0].Width, dataGridView1.Rows[0].Height);
e.Graphics.DrawString(dataGridView2.Rows[i].Cells["Column3"].FormattedValue.ToString(), dataGridView2.Font, Brushes.Black, CurrentX, CurrentY + 20);
e.Graphics.DrawString(dataGridView2.Rows[i].Cells["Column4"].FormattedValue.ToString(), dataGridView2.Font, Brushes.Black, CurrentX + 150, CurrentY + 20);
// e.Graphics.DrawString(dataGridView2.Rows[i].Cells["Column5"].FormattedValue.ToString(), dataGridView2.Font, Brushes.Black, CurrentX + 150, CurrentY + 20);
e.Graphics.DrawString(dataGridView2.Rows[i].Cells["Column10"].FormattedValue.ToString(), dataGridView2.Font, Brushes.Black, CurrentX + 200, CurrentY + 20);
i++;
CurrentY = CurrentY + 20;
}
您实际上并没有在对DrawString
的调用之间增加CurrentY
变量。 因此,每行都以相同的Y坐标打印。
加CurrentY = CurrentY + 20;
在每次调用DrawString并使用之间
e.Graphics.DrawString(dataGridView2.Rows[i].Cells["Column3"].FormattedValue.ToString(), dataGridView2.Font, Brushes.Black, CurrentX, CurrentY);
更好的是,不要将其递增固定值,而是使用e.Graphics.MeasureString
来计算每行的实际高度,并以该值+间距递增,如以下示例所示:
Bitmap bmp = new Bitmap(200, 200);
using (Graphics g = Graphics.FromImage(bmp)) {
//The individual lines to draw
string[] lines = {
"Foo1",
"Foo2",
"Foo3"
};
int y = 1; //The starting Y-coordinate
int spacing = 10; //The space between each line in pixels
for (i = 0; i <= lines.Count - 1; i++) {
g.DrawString(lines[i], this.Font, Brushes.Black, 1, y);
//Increment the coordinate after drawing each line
y += Convert.ToInt32(g.MeasureString(lines[i], this.Font).Height) + spacing;
}
}
PictureBox1.Image = bmp;
编辑
为了使文本适合给定区域,您需要使用不同的DrawString
重载。 您需要使用给定的LayoutRectangle
绘制字符串,如下所示:
Bitmap bmp = new Bitmap(200, 200);
using (Graphics g = Graphics.FromImage(bmp)) {
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
string LongText = "This is a really long text that should be automatically wrapped to a certain rectangle.";
Rectangle DestinationRectangle = new Rectangle(10, 10, 100, 150);
g.DrawRectangle(Pens.Red, DestinationRectangle);
using (StringFormat sf = new StringFormat()) {
g.DrawString(LongText, new Font("Arial", 9), Brushes.Black, DestinationRectangle, sf);
}
}
PictureBox1.Image = bmp;
DestinationRectangle
定义了文本的打印位置,并自动对其进行换行。 问题是,行距由您使用的字体定义,如在本示例中看到的,使用了不同的字体:
如果找不到适合您的字体(或定义自己的字体),则需要将文本拆分为多个单词,然后逐个单词地绘制它们,并使用MeasureString
函数对其进行测量,然后将其拆分,从而将它们调整为给定的矩形超出限制的线。 但是请注意,要正确处理所有常见情况,文本布局非常困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.