本文主要介绍解决在osgEarth中的中文乱码问题。
主要有两个需要注意的点:
1、将字符串从Unicode转换为UTF-8编码:
void unicodeToUTF8(const wstring &src, string& result)
{
int n = WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, 0, 0, 0, 0);
result.resize(n);
::WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, (char*)result.c_str(), result.length(), 0, 0);
}
unicodeToUTF8(L"中国", _strWideName);
2、添加中文字体:
textStyle->font() = "simkai.ttf";
完整代码
//Unicode转UTF-8函数
void unicodeToUTF8(const wstring &src, string& result)
{
int n = WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, 0, 0, 0, 0);
result.resize(n);
::WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, (char*)result.c_str(), result.length(), 0, 0);
}
//显示中文代码
osgEarth::Style style;
osgEarth::Symbology::TextSymbol * textStyle = style.getOrCreateSymbol();
//设置颜色
textStyle->fill()->color() = osg::Vec4f(1.0, 1.0, 1.0, 1.0);
//设置边框
textStyle->halo()->color() = osg::Vec4f(0.0, 0.0, 0.0, 1.0);
textStyle->font() = "simkai.ttf";
textStyle->size() = 20.0;
//textStyle->pixelOffset() = osg::Vec2s(100, 100.0);
textStyle->encoding() = osgEarth::Symbology::TextSymbol::ENCODING_UTF8;
osg::Image* china = osgDB::readImageFile("./label/chinaIcon.jpg");
const osgEarth::SpatialReference* geoSRS = mapNode->getMapSRS()->getGeographicSRS();
std::string _strWideName;
unicodeToUTF8(L"中国", _strWideName);
osgEarth::Annotation::PlaceNode *pn = new osgEarth::Annotation::PlaceNode(mapNode, osgEarth::GeoPoint(geoSRS, 110, 34), china, _strWideName, style);
earthLabel->addChild(pn);