I want to colorize a grayscale CCSprite in cocos2d by programming, for an example, the grayscale CCSprite is:
http://cc.cocimg.com/bbs/attachment/Fid_18/18_171059_43b48b6f1bc40a5.png
the output CCSprite is:
http://cc.cocimg.com/bbs/attachment/Fid_18/18_171059_574b2f34cb78b49.png
But I can not get the correct result.
If I use [CCSprite setColor], I got a CCSprite is dark I used CCRenderTexture and tried two different blendFunc,
-(CCSprite *) try1:(CCSprite *)gray color:(ccColor3B) color
{
CCRenderTexture *rtx = [CCRenderTexture renderTextureWithWidth:gray.contentSize.width height:gray.contentSize.height];
ccColor4F c = ccc4FFromccc3B(color);
[rtx beginWithClear:c.r g:c.g b:c.b a:c.a];
gray.position = ccp(gray.contentSize.width/2, gray.contentSize.height/2);
gray.blendFunc = (ccBlendFunc){GL_ONE_MINUS_SRC_COLOR, GL_SRC_COLOR};
[gray visit];
[rtx end];
CCSprite *sp = [CCSprite spriteWithTexture:rtx.sprite.texture];
sp.flipY = YES;
return sp;
}
the other is:
-(CCSprite *) try2:(CCSprite *)gray color:(ccColor3B) color
{
CCRenderTexture *rtx = [CCRenderTexture renderTextureWithWidth:gray.contentSize.width height:gray.contentSize.height];
ccColor4F c = ccc4FFromccc3B(color);
[rtx beginWithClear:c.r g:c.g b:c.b a:0];
gray.position = ccp(gray.contentSize.width/2, gray.contentSize.height/2);
gray.blendFunc = (ccBlendFunc){GL_SRC_COLOR, GL_SRC_ALPHA};
[gray visit];
[rtx end];
CCSprite *sp = [CCSprite spriteWithTexture:rtx.sprite.texture];
sp.flipY = YES;
return sp;
}
and I even tried shader:
#ifdef GL_ES
precision mediump float;
#endif
uniform sampler2D u_texture;
varying vec2 v_texCoord;
varying vec4 v_fragmentColor;
uniform vec4 u_fillcolor;
#pragma debug(on)
void main(void)
{
vec4 c = texture2D(u_texture, v_texCoord);
float r;
float g;
float b;
r = u_fillcolor.r + (2.0 * c.r - 1.0);
g = u_fillcolor.g + (2.0 * c.g - 1.0);
b = u_fillcolor.b + (2.0 * c.b - 1.0);
gl_FragColor = vec4(r,g,b, c.a);
}
but the outputs are not correct.
Could you help me find a way to output the correct CCSprite?
Thanks.
(I am a new user of stackoverflow, my reputation is not enough for adding images, so I have to add images as links.)
If you are not constantly changing the colors this method will work.
To load a sprite using the above method:
Hope this helps.