cocos2d-x 单色精灵

前端之家收集整理的这篇文章主要介绍了cocos2d-x 单色精灵前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

说说我自己想出的获取一个精灵对应的单色精灵的方法(将一个精灵中不透明部分的颜色全部变成单一颜色,单色精灵这个名字我自己随便取的)

方法一 RenderTexture@H_301_4@

  1. Sprite *getMonoColorSprite(Sprite *sprite)
  2. {
  3. auto size = sprite->getContentSize();
  4. auto anchorPoint = sprite->getAnchorPoint();
  5. auto position = sprite->getPosition();
  6.  
  7. auto center = Vec2(size.width / 2,size.height / 2);
  8.  
  9. //如果直接用sprite,renderTexture上下是反的
  10. //有时sprite的锚点和位置变了,renderTexture里的纹理是空的
  11. //所以创建一个临时的上下翻转的精灵
  12. auto temp = Sprite::createWithTexture(sprite->getTexture(),sprite->getTextureRect());
  13. temp->setPosition(center);
  14. temp->setFlippedY(true);
  15.  
  16. auto mask = LayerColor::create(Color4B::WHITE,size.width,size.height);
  17. mask->setBlendFunc({ GL_DST_ALPHA,GL_ZERO });
  18. auto renderTexture = RenderTexture::create(size.width,size.height);
  19. renderTexture->setAnchorPoint(Vec2::ZERO);
  20. renderTexture->setPosition(Vec2::ZERO);
  21.  
  22. renderTexture->begin();
  23. temp->visit();
  24. mask->visit();
  25. renderTexture->end();
  26.  
  27. //用renderTexture里的纹理创建要返回的精灵
  28. auto tex = renderTexture->getSprite()->getTexture();
  29. auto spr = Sprite::createWithTexture(tex);
  30.  
  31. //恢复到与sprite相同的锚点和位置
  32. spr->setAnchorPoint(anchorPoint);
  33. spr->setPosition(position);
  34.  
  35. return spr;
  36. }
上面的函数返回了一个白色的精灵,然后用setColor可以设置颜色,测试代码如下
  1. auto sprite = Sprite::create("grossini.png");
  2. sprite->setPosition(100,200);
  3.  
  4. auto mono = getMonoColorSprite(sprite);
  5. mono->setColor(Color3B::GREEN);
  6. mono->setPosition(300,200);
  7.  
  8. addChild(sprite);
  9. addChild(mono);



有点像数字图像处理中的图像二值化,不过这里这有一种颜色

使用RenderTexture效率低下,而且要占用额外空间,图片多的话,可能会多占很多空间,这种方法不太实用,推荐使用下面的Shader实现


方法二 Shader@H_301_4@


@H_301_4@

fsh文件如下

  1. #ifdef GL_ES
  2. precision lowp float;
  3. #endif
  4. varying vec4 v_fragmentColor;
  5. varying vec2 v_texCoord;
  6.  
  7.  
  8. void main()
  9. {
  10. vec4 texColor = texture2D(CC_Texture0,v_texCoord);
  11. <span style="white-space:pre"> </span>//最终颜色完全由顶点颜色决定
  12. gl_FragColor=v_fragmentColor;
  13. gl_FragColor.a*=texColor.a;
  14. }

使用方法
  1. //可以在游戏初始化加载Shader,并添加到<span style="font-family: Arial,Helvetica,sans-serif;">ShaderCache中,方便以后调用</span>
  2. auto fragmentSource = FileUtils::getInstance()->getStringFromFile("monocolor.fsh");
  3. auto shader_program = GLProgram::createWithByteArrays(ccPositionTextureColor_noMVP_vert,fragmentSource.c_str());
  4.  
  5. ShaderCache::getInstance()->addGLProgram(shader_program,"monocolor");

  1. //应用使用Shader
  2. sprite->setGLProgram(ShaderCache::getInstance()->getGLProgram("monocolor"));


用Shader实现的代码少而且效率高,推荐使用

猜你在找的Cocos2d-x相关文章