我的收据线不能正确对齐
本文关键字:对齐 不能 我的 | 更新日期: 2023-09-27 18:09:44
我在使用Graphics.DrawString()构建收据时遇到对齐2个变量的问题。我正在努力实现:
<indent>Cash....................500.00
<indent>Master Card............1000.00
<indent>American Express.....10,000.00
这是我现在拥有的
foreach (var item in GC.PAYMENT_Repo) //Entity framework
{
int typeLength = item.type.Length;
int amountLength = item.amount.Length;
Graphics.Drawstring(" " + item.type.PadRight(20, '.') + item.amount.PadLeft(typeLength));
}
这是一个使用Rectangle
和StringFormat
对齐文本的工作概念。下面的样品必须在Control
或PrintDocument
的OnPaint()
中。您也可以创建Form
并覆盖OnPaint
,并粘贴下面的代码:
List<dynamic[]> rows = new List<dynamic[]>();
rows.Add(new dynamic[] { "Cash", 500 });
rows.Add(new dynamic[] { "Master Card", 1000 });
rows.Add(new dynamic[] { "American Express", 10000 });
Graphics g = e.Graphics;
Font f = new Font("Courier New", 8f);
//1st column
StringFormat sf1 = new StringFormat();
sf1.Alignment = StringAlignment.Near;
sf1.LineAlignment = StringAlignment.Center;
//2nd column
StringFormat sf2 = new StringFormat();
sf2.Alignment = StringAlignment.Far;
sf2.LineAlignment = StringAlignment.Center;
for (int i = 0; i < rows.Count; i++)
{
int x = 10; //Change for indentation (where you want the x position), currently 10px
int y = f.Height * i;
int colWidth = 125; //You can change this to set each column's width
Rectangle r1 = new Rectangle(x, y, colWidth, f.Height);
Rectangle r2 = new Rectangle(r1.Right, y, colWidth, f.Height);
g.DrawRectangle(Pens.Black, r1); //Just to debug rect area
g.DrawRectangle(Pens.Black, r2);
g.DrawString(rows[i][0], f, Brushes.Black, r1, sf1);
g.DrawString(rows[i][1].ToString("0.00"), f, Brushes.Black, r2, sf2);
}
这个想法是你使用Rectangle
区域来指定文本的实际位置,你想要它被打印。虽然StringFormat
有助于对齐