PrintPageEventArgs.Graphis中的绘图位置已更改

时间:2017-03-08 17:07:27

标签: c# winforms printing graphics drawing

我正在WinForms项目中工作,我在打印文本时遇到了问题。所以我创建了简单的示例来测试问题。在Form中,我通过使用Form.Graphics手动绘制了两行之间的字符串,并通过在PrintDocument.PrintPage事件中使用PrintPageEventArgs.Graphics再次完成相同的操作。在打印预览中更改了绘图位置。请参阅下图,显示问题(即绘制Form.Graphics和PrintPageEventArgs.Graphics之间的线条不同)。请让我知道为什么绘图位置会改变?

public Form1()
{
    InitializeComponent();
    this.Paint += Form1_Paint;
}

void Document_PrintPage(object sender, PrintPageEventArgs e)
{
    e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Red)), 10, 10, 10, 25);
    e.Graphics.DrawString("Some Chars are getting Cut in Print Preview", this.Font, new SolidBrush(Color.Red), 10, 10);
    e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Red)), 228, 10, 228, 25);
}

void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Red)), 10, 10, 10, 25);
    e.Graphics.DrawString("Some Chars are getting Cut in Print Preview", this.Font, new SolidBrush(Color.Red), 10, 10);
    e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Red)), 228, 10, 228, 25);
}

private void button1_Click(object sender, EventArgs e)
{
    PrintPreviewDialog ppd = new PrintPreviewDialog();
    PrintDocument doc = new PrintDocument();
    ppd.Document = doc;
    ppd.Document.PrintPage += Document_PrintPage;
    ppd.ShowDialog();
}

enter image description here

示例:TestSample

先谢谢。

1 个答案:

答案 0 :(得分:1)

这些职位并不总是一样,请不要使用魔术数字。想想如果改变字体大小会发生什么?

而是考虑使用Graphics.MeasureString

SizeF stringSize = e.Graphics.MeasureString(theText, this.Font);
e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Red)), stringSize.Width + 1, 10, stringSize.Width + 1, 25);

使用此方法,您可以使用stringSize.Height来获取字符串的高度,而不是硬编码25

int lineEndY = 10 + stringSize.Height /* + anyBufferConstant*/;

附注:PenSolidBrush实现IDisposable可能最好将它们包装在using语句中,但您也可以使用Pens.Red来处理此特定情况。您还可以复制可以使用辅助方法的代码。把它放在一起:

private void DoPrintingLogic(Graphics g, string text)    
{
    const Point startPos = new Point(10, 10);

    SizeF stringSize = g.MeasureString(text, this.Font);

    using (SolidBrush redBrush = new SolidBrush(Colors.Red))
    {
        g.DrawLine(Pens.Red, startPos.X, startPos.Y, startPos.X, startPos.Y + stringSize.Height);
        g.DrawString(text, this.Font, redBrush, startPos.X, startPos.Y);
        g.DrawLine(Pens.Red, startPos.X + stringSize.Width, startPos.Y, startPos.X + stringSize.Width, startPos.Y + stringSize.Height);
    }
}

免责声明:所有代码均未经过测试。