OSG中创建字体函数:
osg::Node* CreateText(wchar_t * str,double pos[3],double rgba[4],int textSize ,char * TextName)
{
osg::Vec3 position(pos[0],pos[1],pos[2]);
osg::Vec4 color(rgba[0],rgba[1],rgba[2],rgba[3]);
osg::Geode* geode = new osg::Geode();
//setlocale(LC_ALL,"chs");
char buff[255]="\0";
sprintf(buff,"fonts/%s.TTF",TextName);
std::string caiyun(buff);
//设置状态,关闭灯光
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
//设置字体属性
osgText::Text* text = new osgText::Text;
geode->addDrawable( text );
//设置字体
text->setFont(caiyun);
text->setCharacterSize(textSize);
//设置位置
text->setPosition(position);
text->setText(str);
text->setColor(color);
//setlocale(LC_ALL,"C");
//设置相机
osg::Camera* camera = new osg::CameraNode;
//设置透视矩阵
camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1024,0,768));
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
//得到默认设置
camera->setViewMatrix(osg::Matrix::identity());
//设置背景为透明,否则的话可以设置ClearColor
camera->setClearMask(GL_DEPTH_BUFFER_BIT);
//设置渲染顺序,必须在最后渲染
camera->setRenderOrder(osg::CameraNode::POST_RENDER);
camera->addChild(geode);
return camera;
}
void osgCreateText(char* str,double pos[3],double rgba[4],int textSize ,char * TextName,char *osgNodeName)
{
//...
}
起初我用如下方式:
char *str = "xxx";
size_t len = strlen(str) + 1;
size_t converted = 0;
wchar_t *Wstr;
Wstr = (wchar_t *)malloc(len * sizeof(wchar_t));
mbstowcs_s(&converted,Wstr,len,CStr,_TRUNCATE);
这个方式可以将char* 转换为wchar_t *;
但是经调试,在OSG显示的结果还是为乱码。
后来我测试了一种方式:
osg::ref_ptr text2 = createText(L"你好dfa",osg::Vec3(20,21,0),osg::Vec4(255,255,0,1));
就能成功的在OSG上显示中文。由此可见"L"起了作用,那这个"L"到底是何方圣神呢?
经查询,这个L代表宽字符(unicode);
所有我就将 char * 转换为宽字符,问题就解决了。
代码如下:
//将字符转换为宽字符
int nLen = MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,str,-1,NULL,0);
if (nLen > 0)
{
wchar_t * WStr = new wchar_t[nLen];
MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,str,-1,WStr,nLen);
osg::ref_ptr text = CreateText(WStr,pos,rgba,textSize,TextName);
//....
}