问题描述
我对这两种方法感到困惑.
I am confused about these two methods.
我的理解是Graphics.DrawString()使用GDI +并且是基于图形的实现,而TextRenderer.DrawString()使用GDI并允许多种字体并支持unicode.
My understanding is that Graphics.DrawString() uses GDI+ and is a graphics-based implementation, while TextRenderer.DrawString() uses GDI and allows a large range of fonts and supports unicode.
我的问题是,当我尝试将基于十进制的数字作为百分比打印到打印机上时.我的研究使我相信TextRenderer是更好的选择.
My issue is when I attempt to print decimal-based numbers as percentages to a printer. My research leads me to believe that TextRenderer is a better way to go.
但是,MSDN建议不支持TextRenderer的DrawText方法进行打印.您应该始终使用Graphics类的DrawString方法."
我要使用Graphics.DrawString打印的代码是:
My code to print using Graphics.DrawString is:
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%",为零以下的数字打印"-100%".
This prints "100%" for number between 0 and 1 and "-100% for numbers below zero.
我放置时,
Console.WriteLine(String.Format("{0:0.0%}", value));
在我的打印方法中,该值以正确的格式打印(例如:75.0%),因此我可以确定问题出在Graphics.DrawString()之内.
inside my print method, the value prints in the correct format (eg: 75.0%), so I am pretty sure the problem lies within Graphics.DrawString().
推荐答案
这似乎与Graphics.DrawString
或TextRenderer.DrawString
或Console.Writeline
没有任何关系.
This does not appear to have anything to do with Graphics.DrawString
or TextRenderer.DrawString
or Console.Writeline
.
您提供的格式说明符{0.0%}
不会简单地附加一个百分号.根据MSDN文档此处,%
自定义说明符...
The format specifier you are providing, {0.0%}
, does not simply append a percentage sign. As per the MSDN documentation here, the %
custom specifier ...
在我的测试中,Graphics.DrawString
和Console.WriteLine
在传递相同的值和格式说明符时都表现出相同的行为.
In my tests, both Graphics.DrawString
and Console.WriteLine
exhibit the same behavior when passed the same value and format specifier.
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);
}
}
这篇关于Graphics.DrawString()与TextRenderer.DrawText()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!