MFC 根据字符宽度居中

Gdiplus::Font font(_T("微软雅黑"), (Gdiplus::REAL)130);
						Gdiplus::RectF orgin(0.0f, 100.0f, nWidth, 200.0f);
						Gdiplus::StringFormat stringformat;
						stringformat.SetAlignment(Gdiplus::StringAlignmentCenter);
						//stringformat.SetLineAlignment(Gdiplus::StringAlignmentCenter);
						Gdiplus::SolidBrush solidBrush(Gdiplus::Color(255, 255, 0, 0));
						graphics.DrawString(strFailedContent.c_str(), -1, &font, orgin, &stringformat, &solidBrush);

  函数如下

float GetTextWidthFloor(const wstring& strText, const Gdiplus::Font& font)
{
	Gdiplus::StringFormat stringformat(Gdiplus::StringAlignmentNear);

	Gdiplus::GraphicsPath graphicsPathObj;
	Gdiplus::FontFamily fontfamily;
	font.GetFamily(&fontfamily);

	Gdiplus::RectF rcBound;
	graphicsPathObj.AddString(strText.c_str(), -1, &fontfamily, font.GetStyle(), font.GetSize(), Gdiplus::PointF(0, 0), &stringformat);
	graphicsPathObj.GetBounds(&rcBound);

	return (float)(rcBound.Width);
}

int GetTextWidth(const wstring& strText, const Gdiplus::Font& font)
{
	// calculate spaces width of text head
	// due to gdiplus do not care about it
	int nHeadSpace = 0;
	int nLen = strText.size();
	for (int i=0; i<nLen; ++i)
	{
		if (0x20 == strText.at(i))
			nHeadSpace++;
		else{
			break;
		}
	}

	// calculate space width
	static float fSpaceWidth = 0.0f;
	if ((fSpaceWidth >= -0.00001f && fSpaceWidth <= 0.00001f) && nHeadSpace > 0)
	{
		fSpaceWidth = GetTextWidthFloor(_T("a b"), font) - GetTextWidthFloor(_T("ab"), font);
	}

	float fResult = GetTextWidthFloor(strText, font) + (float)nHeadSpace * fSpaceWidth;

	return (int)fResult + 1;
}

  

posted @ 2015-09-17 18:34  QQ76211822  阅读(519)  评论(0编辑  收藏  举报