我有一列标签,我想制作与最宽文本一样宽的标签。如果我在网页中使用“小”文字大小,是否可以根据可用的最大文本字符串估算标签的宽度?
这适用于带有c#的ASP.net。
谢谢!
答案 0 :(得分:1)
将HTML渲染为虚拟虚拟和隐藏 div,在页面外的某处,然后使用Javascript / jQuery来测量div的大小,该大小随文本一起增长。不要忘记应用css white-space: nowrap;
,以便它永远增长。
答案 1 :(得分:0)
从这开始: http://www.davidthielen.info/programming/2005/10/getting_accurat.html
我能够调整它以获得以下对我有用的代码:
private static float MAX_RECT = 100000;
private static float BITMAP_DPI = 2400;
private static float ADJUST_TO_POINTS = 72.0f / BITMAP_DPI;
public static float GetTextWidth(String fontname, float fontsize, FontStyle style, String text)
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
bmp.SetResolution(BITMAP_DPI, BITMAP_DPI);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bmp);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
System.Drawing.StringFormat fmt = System.Drawing.StringFormat.GenericTypographic;
fmt.Trimming=System.Drawing.StringTrimming.None;
fmt.FormatFlags=System.Drawing.StringFormatFlags.MeasureTrailingSpaces | System.Drawing.StringFormatFlags.NoWrap;
System.Drawing.Font font = new System.Drawing.Font(fontname, fontsize, style, System.Drawing.GraphicsUnit.Point);
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, MAX_RECT, MAX_RECT);
fmt.SetMeasurableCharacterRanges(new System.Drawing.CharacterRange[] { new System.Drawing.CharacterRange(0, text.Length) });
System.Drawing.Region[] rgns = graphics.MeasureCharacterRanges(text, font, rect, fmt);
rect = rgns[0].GetBounds(graphics);
return rect.Width * ADJUST_TO_POINTS;
}
private static float GetLabelWidth(RS2005.ReportParameter[] parameters, String fontname, double fontSizeUnitVal, FontStyle style, String text)
{
float emSize = Convert.ToSingle(fontSizeUnitVal + 1);
emSize = (emSize == 0 ? 12 : emSize);
int pCnt = parameters.Count();
string txt;
float size = 0;
for (int i = 0; i < pCnt; i++)
{
txt = parameters[i].Prompt == null ? parameters[i].Prompt : parameters[i].Name;
var width=GetTextWidth(fontname, emSize, style, txt);
if (width > size)
size = width;
}
return size;
}
我称之为:
size = GetLabelWidth(parameters, pPromptLbl.Font.Name, pPromptLbl.Font.Size.Unit.Value, FontStyle.Bold, pPromptLbl.Text);
pPromptLbl.Width = Unit.Parse(Math.Round(size+30, 0).ToString());