如何在C#中使用MeasureString来设置表列宽度? [英] How to use MeasureString in C# to set table column width?

查看:141
本文介绍了如何在C#中使用MeasureString来设置表列宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常快(我希望基本)的问题。我正在修改我公司网站的一些C#代码。代码在固定列中为我绘制一张表格,其数据从数据库中提取。表格每一列的高度是固定的(当前),我需要改变它,所以如果字符串是一定的长度,因此换行,第二行文本是可见的(而不是隐藏在下一行) 。

从我的研究中,我可以使用MeasureString(因为我知道字体和字符串)来查看字符串是否比我设置的表列更长/更宽如果是这样的话,改变行的高度。不过,我对C#编程非常陌生(除了网络工具外,几年来还没有完成很多编程),所以我不确定如何实现所有这些。我有逻辑,我知道如何改变高度,我只需要知道如何获得一个实际的数字我可以使用逻辑反对使用MeasureString方法(以及如何实例化我可能需要使用的任何变量和函数这个方法)。

解决方案

我相信你需要使用这个重载 MeasureString(string,font,int)


width参数指定返回的SizeF结构(宽度)的宽度分量
的最大值。如果width参数小于字符串的实际宽度
,则返回的宽度分量
被截断为表示最大字符数
的值,该值将在指定的宽度内。 要容纳整个
字符串,返回的Height组件将被调整为值
允许显示带有字符换行的字符串。



- 从上面链接的MSDN页面(Emphasis mine)

  //测量字符串(你需要实例化你自己的图形对象,
//因为你没有PaintEventArgs)
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString,stringFont,stringWidth);
int cellHeight = stringSize.Height;


I have a pretty quick (and I'm hoping basic) question. I'm modifying some C# code for my company's website. The code draws a table for me in fixed columns, the data for which is pulled from a database. The height of the each column of the table is fixed (currently), and I need to change it so if the string is a certain length, and therefore wraps, the second line of text is viewable (instead of hidden by the next row).

From my research, it seems like I can use MeasureString (since I know the font and string) to see if the string is longer/wider than my set table column, and change the height of the row if this is so. However, I'm very new to C# programming (and haven't done much programming overall in years, besides web stuff), so I'm not sure how to get all of this implemented. I have the logic in place, and I know how to change the height, I just need to know how to get an actual number I can use logic against using the MeasureString method (and how to instantiate any variables and functions I might need to use that method).

解决方案

I believe you need to use this overload for MeasureString(string,font,int):

The width parameter specifies the maximum value of the width component of the returned SizeF structure (Width). If the width parameter is less than the actual width of the string, the returned Width component is truncated to a value representing the maximum number of characters that will fit within the specified width. To accommodate the entire string, the returned Height component is adjusted to a value that allows displaying the string with character wrap.

-- From Above Linked MSDN Page (Emphasis mine)

// Measure string (you'll need to instansiate your own graphics object, 
// since you wont have PaintEventArgs)
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth);
int cellHeight = stringSize.Height;

这篇关于如何在C#中使用MeasureString来设置表列宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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