使用GDI+的MeasureString函数来实现这个功能
1、初始化GDI+
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment(lib, "gdiplus")
2、判断长度等
下面这个是判断字符串长度超过240像素后,先获取字符串在240以内部分,然后超出的部分加"..."显示
Graphics gra(hdcBuffer);
//首先创建字体相关
FontFamily fontFamily(TEXT("Arial")); //字体
Font font(&fontFamily, 20, FontStyleRegular, UnitPixel); //30为字号,就是文字的大小
PointF pointF(0.0f, 0.0f); //绘画的x、y坐标
WCHAR string[256];
RectF boundRect; //作为MeasureString的参数,调用MeasureString后会把x、y、高度和宽度填入boundRect里
for (int i = 0; i < 100; i++)
{
AmpChildName_15[i] = AmpChildName[i];
lstrcpynW(string, (LPCTSTR)AmpChildName_15[i], AmpChildName_15[i].GetLength());//CString转换为WCHAR
gra.MeasureString(string, wcslen(string), &font, pointF, &boundRect);//使用GDI+获取字符串像素大小
if (boundRect.Width > 240)//字符串像素宽度
{
//根据长度,一个个来减少字符,直到字符串小于240,多余部分显示...
for (int j = 0; j < AmpChildName_15[i].GetLength(); j++)
{
lstrcpynW(string, (LPCTSTR)AmpChildName_15[i], AmpChildName_15[i].GetLength() - j);//
gra.MeasureString(string, wcslen(string), &font, pointF, &boundRect);
if (boundRect.Width <= 240)
{
AmpChildName_15[i] = AmpChildName_15[i].Mid(0, AmpChildName_15[i].GetLength() - j) + "...";
break;
}
}
}
}