WIN32开发之判断字符串像素宽度

使用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;
							}
						}
					}
				
			}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值