通过格式化双值来绘制对齐的字符串 [英] Drawing aligned strings by formatting double values
问题描述
我正在创建一个创建双数组表的用户控件.我能够绘制它们,但我不知道如何对齐这些值.
I am creating a user control which creates a table of a double array. I am able to draw them but I don't know how align the values.
示例:我的数据看起来像
Example: my data looks like
double[] data = new double[]
{
-13.5,
-8.5,
-3.5,
0,
3.5,
8.5,
13.5
};
所以我希望当我绘制这些值时,它们应该对齐(右对齐),以便所有值的点都出现在同一位置.
so i want that when i draw these values they should be aligned (right aligned) so the dot appears exactly on same place for all values.
这是我使用的代码:
private void DrawTable()
{
_format.Alignment = StringAlignment.Far;
_format.LineAlignment = StringAlignment.Far;
int yPos = 2;
RectangleF rect = RectangleF.Empty;
foreach (var item in Data)
{
string str = item.ToString("F3");
str = string.Format("{0}dB", str);
str = string.Format("{0,10}",str);
SizeF size = _gBmp.MeasureString(str, Font);
rect.X = 5;
rect.Y = yPos;
rect.Width = size.Width;
rect.Height = size.Height;
_gBmp.DrawString(str, Font, _textBrush, rect, _format);
yPos += 20;
}
}
推荐答案
问题是您正在通过测量字符串的大小创建的矩形中绘制每个项目.
The problem is that you are drawing each item in a rectangle which you create by measuring the size of the string.
您需要为您绘制的每个字符串使用相同宽度的矩形.然后,如果您将字符串右对齐,它们将对齐(前提是您使用相同的字体).
You instead need to use the same width rectangle for each string you draw. Then if you right-align the strings they will line up (provided you're using the same font).
不要使用 String.Format
填充来填充字符串.这不是使用 GDI+ 的正确方法,它主要用于固定宽度字体,如控制台显示.您唯一要使用字符串格式的方法是指定固定的小数位数.
Do not use the String.Format
padding to pad the strings for you. It's not the right way to do it with GDI+ and it's mainly for fixed-width fonts like a console display. The only thing you want to use string formatting for is to specify a fixed number of decimal places.
如果我希望列的宽度通常动态调整大小,我要做的是测量列表中的每个元素,然后选择所有测量宽度的最大宽度.但是,通常您希望将其夹到最大宽度,以防万一您的字符串非常长.
If I want the width of the column to be dynamically sized normally what I do is measure every element in the list and then select the maximum width of all of the measured widths. Usually you want to clamp it to a max width in case you have a really long string, though.
这篇关于通过格式化双值来绘制对齐的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!