You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Graphics.DrawString打印时多行重叠问题求助

解决DrawString打印收据内容重叠的问题

问题根源

  1. 坐标未递增:你调用DrawString时,多个文本块用了相同的pos垂直坐标,比如地址、邮编、城镇都绑定pos,感谢语也用pos,导致所有内容都画在同一垂直位置,自然重叠。
  2. 未启用换行支持:默认情况下Graphics.DrawString不会识别字符串里的\n换行符,必须通过StringFormat显式开启换行功能。
  3. 字符串换行写法错误:代码里的字符串直接换行(比如"***The Android Dungeon*** \n"的写法不符合C#语法),字符串内的换行应该用\n转义,或者用逐字字符串@""包裹。

修复后的代码示例

// 创建支持换行的格式配置
StringFormat stringFormat = new StringFormat();
stringFormat.AllowLineBreaks = true;
stringFormat.LineAlignment = StringAlignment.Near;

// 初始化垂直起始位置
float currentY = pos;

// 定义字体(复用减少资源消耗)
Font smallBoldFont = new Font("Century Gothic", 8, FontStyle.Bold);
Font largeBoldFont = new Font("Century Gothic", 12, FontStyle.Bold);

// 绘制感谢语
string thankYouText = $"Thank you - {CusName.Text}\n";
SizeF textSize = e.Graphics.MeasureString(thankYouText, smallBoldFont);
e.Graphics.DrawString(thankYouText, smallBoldFont, Brushes.Blue, new PointF(40, currentY), stringFormat);
currentY += textSize.Height + 5; // 增加上下间距

// 绘制地址
string addressText = $"{Addresstb.Text}\n";
textSize = e.Graphics.MeasureString(addressText, smallBoldFont);
e.Graphics.DrawString(addressText, smallBoldFont, Brushes.Blue, new PointF(80, currentY), stringFormat);
currentY += textSize.Height + 5;

// 绘制邮编
string postcodeText = $"{Postcodetb.Text}\n";
textSize = e.Graphics.MeasureString(postcodeText, smallBoldFont);
e.Graphics.DrawString(postcodeText, smallBoldFont, Brushes.Blue, new PointF(100, currentY), stringFormat);
currentY += textSize.Height + 5;

// 绘制城镇
string townText = $"{towntb.Text}\n";
textSize = e.Graphics.MeasureString(townText, smallBoldFont);
e.Graphics.DrawString(townText, smallBoldFont, Brushes.Blue, new PointF(120, currentY), stringFormat);
currentY += textSize.Height + 20; // 增加额外间距区分区块

// 绘制总计
string totalText = $"Grand Total: £ {grdtotal}";
textSize = e.Graphics.MeasureString(totalText, largeBoldFont);
e.Graphics.DrawString(totalText, largeBoldFont, Brushes.Crimson, new PointF(60, currentY), stringFormat);
currentY += textSize.Height + 15;

// 绘制店铺名称
string shopText = "***The Android Dungeon***";
e.Graphics.DrawString(shopText, largeBoldFont, Brushes.Crimson, new PointF(40, currentY), stringFormat);

// 释放资源
smallBoldFont.Dispose();
largeBoldFont.Dispose();
stringFormat.Dispose();

关键修复点

  • 用MeasureString计算文本高度:每次绘制后,把currentY增加文本高度+额外间距,确保下一段文本在下方。
  • 启用StringFormat换行:设置AllowLineBreaks = true,让DrawString识别\n实现换行。
  • 统一管理垂直坐标:用currentY代替固定的pos,逐步递增位置避免重叠。
  • 规范字符串拼接:用字符串插值$""拼接内容,换行符统一用\n。

内容的提问来源于stack exchange,提问作者jacksonb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:25:24