转载请注明出处:http://www.cnblogs.com/Ray1024
一、问题描述
二、问题分析
这个问题出现之后,我设置断点定位到CRenderTarget::DrawText()调用处,F11进入afxrendertarget.cpp文件中的函数CRenderTarget::DrawText() 内部,查看函数如下:
void CRenderTarget::DrawText(const CString& strText, const CD2DRectF& rect, CD2DBrush* pForegroundBrush, CD2DTextFormat* textFormat, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode) { USES_CONVERSION; if (m_pRenderTarget == NULL) { ASSERT(FALSE); return; } if (!VerifyResource(pForegroundBrush)) { return; } if (textFormat == NULL) { // Use default text format if (m_pTextFormatDefault == NULL) { NONCLIENTMETRICS NonClientMetrics; NonClientMetrics.cbSize = sizeof(NONCLIENTMETRICS); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, NonClientMetrics.cbSize, &NonClientMetrics, 0); m_pTextFormatDefault = new CD2DTextFormat(this, NonClientMetrics.lfMenuFont.lfFaceName, (FLOAT)abs(NonClientMetrics.lfMenuFont.lfHeight)); } textFormat = m_pTextFormatDefault; } if (!textFormat->IsValid()) { ASSERT(FALSE); return; } m_pRenderTarget->DrawText(T2CW(strText), strText.GetLength(), textFormat->m_pTextFormat, &rect, *pForegroundBrush, options, measuringMode); }
这是CRenderTarget封装的DrawText,内部使用ID2D1RenderTarget对象调用DrawText函数,第一个参数为宽字节字符串,第二个参数为宽字节字符串的长度。
三、解决方案
CString strText(_T("中文Hello, World!")); //pRenderTarget->DrawText(strText, rect, m_pBlackBrush, m_pTextFormat); // 把原来的DrawText替换成这个 USES_CONVERSION; pRenderTarget->GetHwndRenderTarget()->DrawText( T2CW(strText), wcslen(T2CW(strText)), m_pTextFormat->Get(), &D2D1::Rect(rect.left, rect.top, rect.right, rect.bottom), m_pBlackBrush->Get());
当然,我们也可以直接改工程编码方式为Unicode编码,这样也不会出现乱码(简单粗暴,哈哈),只是有些工程出于种种原因只能用多字节编码方式,这样就可以使用上面的方法了。
搞定!