我正在生成一个收据,并使用Graphics对象调用DrawString方法打印出所需的文本.
graphics.DrawString(string, font, brush, widthOfPage / 2F, yPoint, stringformat);
Run Code Online (Sandbox Code Playgroud)
这适用于我需要它做的事情.我总是知道我要打印出来的东西,所以我可以手动修剪任何琴弦,这样它就可以正确地放在80毫米的收据纸上.然后我不得不添加额外的功能,这将使这更灵活.用户可以传入将添加到底部的字符串.
由于我不知道他们要放什么,我只是创建了自己的自动换行功能,它包含了许多字符来包装和字符串本身.为了找出字符数,我做了这样的事情:
float width = document.DefaultPageSettings.PrintableArea.Width;
int max = (int)(width / graphics.MeasureString("a", font).Width);
Run Code Online (Sandbox Code Playgroud)
现在宽度正在返回283,以mm为单位约为72,这在80mm纸张上考虑边距时是有意义的.
但MeasureString方法在Courier New 8pt字体上返回10.5.因此,不是绕过我期望的36 - 40,我得到26,导致2行文本变成3-4.
PrintableArea.Width的单位是1/100英寸,图形对象的PageUnit是Display(对于打印机来说通常是1/100英寸).那么为什么我只回来26?
我经常搜索并尝试了很多,但我找不到合适的解决方案.
我想知道有没有办法确定指定字体的确切字形高度?
我的意思是在这里,当我想确定DOT字形的高度时,我应该获得较小的高度,但不能使用填充或字体大小来获得高度.
我已经找到了确定的解决方案准确字形宽度在这里(我用第二种方法),但它并不适用于高度工作.
更新:我需要.NET 1.1的解决方案
为什么我必须将MeasureString()结果宽度增加21%
size.Width = size.Width * 1.21f;
来逃避Word Wrap DrawString()?
我需要一个解决方案来获得确切的结果.
相同的字体,相同的字符串格式,两个函数中使用的文本相同.
从OP回答:
SizeF size = graphics.MeasureString(element.Currency, Currencyfont, new PointF(0, 0), strFormatLeft);
size.Width = size.Width * 1.21f;
int freespace = rect.Width - (int)size.Width;
if (freespace < ImageSize) { if (freespace > 0) ImageSize = freespace; else ImageSize = 0; }
int FlagY = y + (CurrencySize - ImageSize) / 2;
int FlagX = (freespace - ImageSize) / 2;
graphics.DrawImage(GetResourseImage(@"Flags." + element.Flag.ToUpper() + ".png"),
new Rectangle(FlagX, FlagY, ImageSize, ImageSize)); …Run Code Online (Sandbox Code Playgroud) 也许我错了,但是...我想模拟字符间距.我将单词(文本)分成单个字符列表,测量它们的宽度,然后在位图上一个接一个地绘制它们.我想,渲染文本的整体宽度将与整个未分割字符串的宽度相同,但有一些错误.在循环中渲染字符显示更广泛的结果.有没有办法获得共同(预期)的结果?
这是一段代码:
private struct CharWidths
{
public char Char;
public float Width;
}
private List<CharWidths> CharacterWidths = new List<CharWidths>();
Run Code Online (Sandbox Code Playgroud)
...
private void GetCharacterWidths(string Text, Bitmap BMP)
{
int i;
int l = Text.Length;
CharacterWidths.Clear();
Graphics g = Graphics.FromImage(BMP);
CharWidths cw = new CharWidths();
for (i = 0; i < l; i++)
{
Size textSize = TextRenderer.MeasureText(Text[i].ToString(), Font);
cw.Char = Text[i];
cw.Width = textSize.Width;
CharacterWidths.Add(cw);
}
}
Run Code Online (Sandbox Code Playgroud)
...
public void RenderToBitmap(Bitmap BMP)
{
//MessageBox.Show("color");
Graphics g = Graphics.FromImage(BMP);
GetCharacterWidths("Lyborko", BMP);
int …Run Code Online (Sandbox Code Playgroud)