Graphics.DrawString()vs TextRenderer.DrawText()

Mar*_*mes 7 c# drawstring

我对这两种方法感到困惑.

我的理解是Graphics.DrawString()使用GDI +并且是基于图形的实现,而TextRenderer.DrawString()使用GDI并允许大量字体并支持unicode.

我的问题是当我尝试将基于十进制的数字打印为打印机的百分比时.我的研究让我相信TextRenderer是一个更好的方法.

但是,MSDN建议,"TextRenderer的DrawText方法不支持打印.您应该始终使用Graphics类的DrawString方法."

我使用Graphics.DrawString打印的代码是:

if (value != 0)
    e.Graphics.DrawString(String.Format("{0:0.0%}", value), GetFont("Arial", 12, "Regular"), GetBrush("Black"), HorizontalOffset + X, VerticleOffset + Y);
Run Code Online (Sandbox Code Playgroud)

对于0到1之间的数字打印"100%",对于零以下的数字打印"-100%".

我放的时候

Console.WriteLine(String.Format("{0:0.0%}", value));
Run Code Online (Sandbox Code Playgroud)

在我的print方法中,值以正确的格式打印(例如:75.0%),所以我很确定问题出在Graphics.DrawString()中.

Liq*_*ony 2

Graphics.DrawString这似乎与或TextRenderer.DrawString或没有任何关系Console.Writeline

您提供的格式说明符{0.0%}并不简单地附加百分号。根据此处的MSDN 文档,%自定义说明符...

导致数字在格式化之前乘以 100。

在我的测试中,当传递相同的值和格式说明符时,Graphics.DrawString和都表现出相同的行为。Console.WriteLine

Console.WriteLine测试:

class Program
{
    static void Main(string[] args)
    {
        double value = .5;
        var fv = string.Format("{0:0.0%}", value);
        Console.WriteLine(fv);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

Graphics.DrawString测试:

public partial class Form1 : Form
{
    private PictureBox box = new PictureBox();

    public Form1()
    {
        InitializeComponent();
        this.Load += new EventHandler(Form1_Load);
    }

    public void Form1_Load(object sender, EventArgs e)
    {
        box.Dock = DockStyle.Fill;
        box.BackColor = Color.White;

        box.Paint += new PaintEventHandler(DrawTest);
        this.Controls.Add(box);
    }

    public void DrawTest(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        double value = .5;
        var fs = string.Format("{0:0.0%}", value);
        var font = new Font("Arial", 12);
        var brush = new SolidBrush(Color.Black);
        var point = new PointF(100.0F, 100.0F);

        g.DrawString(fs, font, brush, point);
    }
}
Run Code Online (Sandbox Code Playgroud)