日期:2014-05-17  浏览次数:20389 次

判断文字是否折行
有这样一个需求,
输入参数为:一个string的字符串, 一个Font对象(包含FontFamily,FontSize,FontStyle等),一个int型的宽度
要求输出为:这个string字符串在指定的宽度内显示时是否会换行?

比如我要显示abcdefghijklmn123这个字符串, 显示的字体是Arial, 字号12px, 粗体, 要显示在宽度为80px的宽度区域内, 我们如何判断这个字符串是否会折行显示?

文字换行 计算字符串长度 计算文字长度 判断折行

------解决方案--------------------
你可以用一个span 包裹起来

然后用jquery获取下宽度,试下

$("span").width();
------解决方案--------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
namespace WebApplication4
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{    
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
Bitmap newBitmap = new Bitmap(600,400,PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(newBitmap);
Font f = new Font("宋体", 12);  //字体不同,测量的宽度不同
SizeF siF =g.MeasureString(TextBox1.Text, f); 
Label1.Text="字符串宽度:"+siF.Width.ToString(); 
Label2.Text="字符串高度:"+siF.Height.ToString();

}
}