给定以下代码。第一个 DrawString 方法是否有可能在 Arial 而不是 Times New Roman 中绘制?
protected override void OnPaint(PaintEventArgs pe)
{
Font f = new Font("Times New Roman", this.TextSize);
pe.Graphics.DrawString("Test 1", f, Brushes.Black, loc);
f = new Font("Arial", this.TextSize);
pe.Graphics.DrawString("Test 2", f, Brushes.Black, loc);
}
我有一个问题,基本上这段代码会间歇性地以错误的字体绘制第一个字符串。我现在已将代码更改为具有两个静态字体引用,但由于我无法重现代码,我无法确定它是否解决了问题。
注意: loc 是一个可以被实际代码改变的位置,我在这里去掉了一些代码来简化
这是我修复的整个方法。如果你看不出它有什么问题——我会去责怪一些宇宙射线之类的……
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (bcf == null)
{
FontFamily[] families = pfc.Families;
foreach (FontFamily ff in families)
{
if (ff.Name.Equals("Free 3 of 9"))
{
bcf = ff;
}
}
}
if (bcf != null)
{
Font f = new Font(bcf, this.BarcodeSize);
SizeF s = TextRenderer.MeasureText(barcodeValue, f);
Rectangle r = pe.ClipRectangle;
Point loc = new Point(0, 0);
if (s.Width < r.Width)
{
loc.X = (int)Math.Ceiling((r.Width - s.Width) / 2);
}
pe.Graphics.DrawString(barcodeValue, f, Brushes.Black, loc);
float barcodeBottom = s.Height + 5;
Font fp = new Font("Arial", this.TextSize);
s = TextRenderer.MeasureText(barcodeValue, fp);
r = pe.ClipRectangle;
loc = new Point(0, (int)Math.Ceiling(barcodeBottom));
if (s.Width < r.Width)
{
loc.X = (int)Math.Ceiling((r.Width - s.Width) / 2);
}
if (s.Height + loc.Y > r.Height)
{
loc.Y = (int)Math.Ceiling(r.Height - (s.Height));
}
pe.Graphics.FillRectangle(Brushes.White, new Rectangle(loc, new Size((int)Math.Ceiling(s.Width), (int)Math.Ceiling(s.Height))));
pe.Graphics.DrawString(barcodeValue, fp, Brushes.Black, loc);
}
}
固定代码现在如下所示。现在更少的 GDI 调用:
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (bcf != null)
{
Rectangle r = pe.ClipRectangle;
Point loc = new Point(0, 0);
if (barcodeDimensions.Width < r.Width)
{
loc.X = (int)Math.Ceiling((r.Width - barcodeDimensions.Width) / 2);
}
pe.Graphics.DrawString(barcodeValue, barcodeFont, Brushes.Black, loc);
float barcodeBottom = barcodeDimensions.Height + 5;
r = pe.ClipRectangle;
loc = new Point(0, (int)Math.Ceiling(barcodeBottom));
if (plaintextDimensions.Width < r.Width)
{
loc.X = (int)Math.Ceiling((r.Width - plaintextDimensions.Width) / 2);
}
if (plaintextDimensions.Height + loc.Y > r.Height)
{
loc.Y = (int)Math.Ceiling(r.Height - (plaintextDimensions.Height));
}
pe.Graphics.FillRectangle(Brushes.White, new Rectangle(loc, new Size((int)Math.Ceiling(plaintextDimensions.Width), (int)Math.Ceiling(plaintextDimensions.Height))));
pe.Graphics.DrawString(barcodeValue, plaintextFont, Brushes.Black, loc);
}
}
如果我打算让它变得更加优化,我会将矩形测量部分放在 OnResize 的覆盖中,但我认为现在可以这样做......