OSG中使用png图片显示透明效果

      常见的几种图片格式中只有png格式和gif格式的图片会有透明效果,其他图片格式都会使用白色作为底色。下面是使用OSG实现png纹理透明效果的代码,使用gif格式的图片也可以,注意:图片必须首先有透明的部分。

#pragma comment(lib, "osg.lib")
#pragma comment(lib, "osgDB.lib")
#pragma comment(lib, "osgViewer.lib")

#include  "osgViewer/Viewer"
#include  "osgDB/ReadFile"
#include  "osg/Node"
#include "osg/Shape"
#include "osg/Geode"
#include "osg/ShapeDrawable"
#include <osg/Texture2D>

int main(){
	//初始化视景器
	osg::ref_ptr<osgViewer::Viewer> viewer=new osgViewer::Viewer;

	//初始化场景根节点
	osg::ref_ptr<osg::Group> root=new osg::Group;

	//创建几何体
	osg::ref_ptr<osg::Geode> geode=new osg::Geode();
	osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
	geode->addDrawable(geometry);

	//将数据加入视景器中
	root->addChild(geode);
	viewer->setSceneData(root);

	//光照模式关闭,这样从各个方向看到的图片才是一样的
	geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);

	//指定几何体的顶点坐标
	osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array();
	v->push_back(osg::Vec3(-1.0, 0.0, -1.0));
	v->push_back(osg::Vec3(1.0, 0.0, -1.0));
	v->push_back(osg::Vec3(1.0, 0.0, 1.0));
	v->push_back(osg::Vec3(-1.0, 0.0, 1.0));
	geometry->setVertexArray(v.get());

	//指定几何体的法向量坐标
	osg::ref_ptr<osg::Vec3Array> normal = new osg::Vec3Array;
	normal->push_back(osg::Y_AXIS);
	geometry->setNormalArray(normal.get());
	geometry->setNormalBinding(osg::Geometry::BIND_OVERALL);

	//指定几何体的纹理坐标
	osg::ref_ptr<osg::Vec2Array> tcoords = new osg::Vec2Array();
	tcoords->push_back(osg::Vec2(0.0f,0.0f));
	tcoords->push_back(osg::Vec2(1.0f,0.0f));
	tcoords->push_back(osg::Vec2(1.0f,1.0f));
	tcoords->push_back(osg::Vec2(0.0f,1.0f));
	geometry->setTexCoordArray(0, tcoords.get());

	//使用图元绘制几何体
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4));

	//贴纹理,这里使用png格式或gif格式的透明图片都可以,但是只能是这两种格式,因为只有这两种格式的图片才可以实现透明
	osg::ref_ptr<osg::Texture2D> texture=new osg::Texture2D;
	//osg::ref_ptr<osg::Image> image=osgDB::readImageFile("forestWall.png");
	osg::ref_ptr<osg::Image> image=osgDB::readImageFile("zhen.gif");

	texture->setImage(image);
	geometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
	
	//要想看到png图片的透明效果,需要开启混合模式
	geometry->getOrCreateStateSet()->setMode(GL_BLEND,osg::StateAttribute::ON);
	geometry->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

	return viewer->run();
}

      运行效果截图:


      这样图片透明的部分便不会显示了。

      源代码下载:下载地址


你可能感兴趣的:(透明,png,OSG)