如何测量给定字体/大小的数字的像素宽度(C#) [英] How to measure the pixel width of a digit in a given font / size (C#)

查看:520
本文介绍了如何测量给定字体/大小的数字的像素宽度(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算Excel列的像素宽度,如

I am trying to calculate the pixel width of Excel columns, as described in this post, using the official formula from the OpenXML specification. However, in order to apply this formula, I need to know the Maximum Digit Width of the Normal font, which is the pixel width of the widest numeric digit. The OpenXML specification gives this example as a clarification:

以Calibri字体为例,最大11磅字体的数字宽度 大小为7像素(在96 dpi时).

Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).

我已经通过肉眼检查Calibri 11点数字来检查这是正确的,并且确实是7像素宽.因此,我正在尝试创建一种方法,该方法将返回任何字体/大小的最大数字宽度.

I have checked that this is correct by visually examining a Calibri 11-point digit and it is indeed 7 pixels wide. So, I am trying to create a method that will return the maximum digit width for any font / size.

我遵循了此问题中的建议,但不会产生我期望的结果.

I have followed the recommendations made in this question, but it doesn't produce the results I am expecting.

这是我的测试代码:

var font = new Font("Calibri", 11.0f, FontStyle.Regular);

for (var i = 0; i < 10; i++)
{
    Debug.WriteLine(TextRenderer.MeasureText(i.ToString(), font));
}

这将报告所有数字的宽度为15.

This reports that all digits have a width of 15.

有什么建议吗?

谢谢, 蒂姆

推荐答案

首先,我要说的是我要显示的代码看起来像是一个可怕的骇客,我并没有将其作为解决方案.相反,我希望它能揭示有关MeasureText行为的更多信息,这可能会导致您最终解决方案.

First let me say that the code I'm about to show looks like a horrible hack and I'm not presenting it as a solution. Rather, I'm hoping it reveals a little more about the behavior of MeasureText that might lead you to your final solution.

我对您的代码做了些微改动.我正在测量两个下划线字符的长度.然后,在for循环的主体中,我用两边的下划线测量所需的字符,并减去两个下划线字符的长度.对于测试方案,我得到的结果为7.其主要目的是确定MeasureText是考虑逐个字符填充还是在字符串的开始/结尾填充.似乎是后者.也许,再加上您收到的一些其他输入,将为您提供一个更优雅的解决方案.

I made a slight alteration to your code. I'm measuring the length of two underscore characters. Then, in the body of the for loop I'm measuring the desired character with underscores on either side and subtracting the length of the two underscore characters alone. For the test scenario I am getting a result of 7. The main purpose of this was to determine whether MeasureText is accounting for padding on a character-by-character basis or padding at the beginning/ending of the string. It seems that it is the latter. Perhaps this, combined with some of the other input you've received, will lead you to a more elegant solution.

var font = new Font("Calibri", 11.0f, FontStyle.Regular);
int underscoreWidth = TextRenderer.MeasureText("__", font).Width; 
for (var i = 0; i < 10; i++)
   {
      int charWidth = TextRenderer.MeasureText(String.Concat("_", i.ToString(), "_"), font).Width - underscoreWidth;
      Debug.WriteLine(charWidth);
   }

这篇关于如何测量给定字体/大小的数字的像素宽度(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆