Create font function in OSG:
<pre name="code" class="cpp">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); //Set the state, turn off the light osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); //set font properties osgText::Text* text = new osgText::Text; geode->addDrawable( text ); //set font text->setFont(caiyun); text->setCharacterSize(textSize); //set the location text->setPosition(position); text->setText(str); text->setColor(color); //setlocale(LC_ALL,"C"); //set the camera osg::Camera* camera = new osg::CameraNode; //Set the perspective matrix camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1024,0,768)); camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); // get default settings camera->setViewMatrix(osg::Matrix::identity()); //Set the background to transparent, otherwise you can set ClearColor camera->setClearMask(GL_DEPTH_BUFFER_BIT); //Set the rendering order, it must be rendered last camera->setRenderOrder(osg::CameraNode::POST_RENDER); camera->addChild(geode); return camera; }
call the create font function
<pre name="code" class="cpp">void osgCreateText(char* str,double pos[3],double rgba[4],int textSize ,char * TextName,char *osgNodeName) { //... }
Here is the job of converting the char * to the wchar_t * type.
At first I used the following way:
<pre name="code" class="cpp">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);
This way can convert char* to wchar_t *;
But after debugging, the result displayed in OSG is still garbled.
Later I tested a way:
<pre name="code" class="cpp">osg::ref_ptr<osg::Node> text2 = createText(L"你好dfa",osg::Vec3(20,21,0),osg::Vec4(255,255,0,1));
Can successfully display Chinese on OSG. It can be seen that "L" has a role to play, so what kind of holy spirit is this "L"?
Upon query, this L stands for wide character (unicode);
All I did was convert the char * to wide char and the problem was solved.
code show as below:
<pre name="code" class="cpp"> //Convert characters to wide characters 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<osg::Node> text = CreateText(WStr,pos,rgba,textSize,TextName); //.... }