7

私はこれらの2つの方法について混乱しています。

私の理解では、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);

これにより、0から1までの数値の場合は「100%」が出力され、0未満の数値の場合は「-100%」が出力されます。

私が置くとき、

Console.WriteLine(String.Format("{0:0.0%}", value));

私のprintメソッド内では、値は正しい形式(例:75.0%)で出力されるため、問題はGraphics.DrawString()内にあると確信しています。

4

1 に答える 1

2

Graphics.DrawStringこれはorとは何の関係もないよう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();
    }
}

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);
    }
}
于 2012-02-06T17:05:55.127 に答える