winforms 为什么我的4行在打印时全部打印在彼此的顶部

z9smfwbn  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(139)
e.Graphics.DrawString("Grand Total: £ " +grdtotal , new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Crimson, new Point(60, pos + 50));
e.Graphics.DrawString("***The Android Dungeon*** \n", new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Crimson, new Point(40, pos + 85));
e.Graphics.DrawString("Thank you - " + CusName.Text + "\n" , new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(40, pos));
            
e.Graphics.DrawString("\n" + Addresstb.Text + "\n", new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(80, pos )); 
            
e.Graphics.DrawString("\n" + Postcodetb.Text + "\n", new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(100, pos )); 
            
e.Graphics.DrawString("\n" + towntb.Text + "\n", new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(120, pos ));

当我打印收据时,所有的收据都打印在彼此的顶部,而这意味着是不同的行。我使用了\n
打印在不同的行上,但它们都打印在彼此的顶部,不应该是这样的,我把\n,它仍然没有打印在一个新的行?

pgccezyw

pgccezyw1#

让我们改进您的示例-注意备注

// You are using 2 different Font sizes, so let's create reusable instances:
var fontBigBold = new Font("Century Gothic", 12, FontStyle.Bold);
var fontNormal  = new Font("Century Gothic", 8, FontStyle.Bold);

// Let's shorten the Brushes, too for Readablity
var crimson = Brushes.Crimson;
var blue = Brushes.Blue;

// let's have the computer compute, not our brain.
var linePtr = pos + 50;

e.Graphics.DrawString($"Grand Total: £ {grdtotal}" , 
               fontBigBold , crimson, 
               new Point(60, linePtr)); // <-- you already were on the right track!?
linePtr += 35;
// \n does nothing for you! Let's ditch those.
e.Graphics.DrawString("***The Android Dungeon***", fontBigBold , crimson, new Point(40, linePtr));
linePtr += 35;
e.Graphics.DrawString($"Thank you - {CusName.Text}" , fontNormal, blue, new Point(40, linePtr));
linePtr += 35;            
e.Graphics.DrawString($"{Addresstb.Text}", fontNormal, blue, new Point(40, linePtr)); 
linePtr += 35;
e.Graphics.DrawString($"{Postcodetb.Text}", fontNormal, blue, new Point(40, linePtr)); 
linePtr += 35;
e.Graphics.DrawString($"{towntb.Text}", fontNormal, blue, new Point(40, linePtr));

为了简单起见,我在这里假设行高为35,如果只是行高的话,我可以用MeasureString加上一个“M”来得到行高,这很有趣。
像这样

int lineHeight = (int)e.Graphics.MeasureString("M", fontBigBold).Height + somePadding;

进一步改进:

  • 我会尝试重构,这样重复的部分就在函数中,而这段代码可以专注于实际用途。
  • 我会再次使用MeasureString确保字符串不会变得太大(太长)。对于这种情况,你可以想到不同的解决方案,如省略号或换行......由你决定。

相关问题