截取指定像素长度的字符串
/// <summary>
/// 截取指定像素长度的字符串
/// </summary>
/// <param name="str">需要截取的字符串</param>
/// <param name="length">像素长度</param>
/// <returns></returns>
public static string GetStringByPixel(string str, int length)
{
Bitmap bmp = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(bmp);
float width = 0;
SizeF sizeF;
Font f = new Font("宋体", 13);
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
sizeF = graphics.MeasureString(c.ToString(), f);
width += sizeF.Width;
if (width > length)
return sb.ToString();
else
sb.Append(c);
}
graphics.Dispose();
bmp.Dispose();
return sb.ToString();
}