Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocos2d: Solid color rectangular sprite?

I must be missing something!

I want to create a solid rectangular CCSprite with a background color initialized to a particular RGB value. I have looked all over the docs and can't find anything.

Is there a way to initialize the background of CCSprite to a specific color? I don't want to have to include a solid color PNG for each colors that I will need.

Help!

like image 621
poundev23 Avatar asked Jul 27 '10 00:07

poundev23


2 Answers

Do it with code! if you don't want to mess with image files, here's your method:

- (CCSprite*)blankSpriteWithSize:(CGSize)size
{
    CCSprite *sprite = [CCSprite node];
    GLubyte *buffer = malloc(sizeof(GLubyte)*4);
    for (int i=0;i<4;i++) {buffer[i]=255;}
    CCTexture2D *tex = [[CCTexture2D alloc] initWithData:buffer pixelFormat:kCCTexture2DPixelFormat_RGB5A1 pixelsWide:1 pixelsHigh:1 contentSize:size];
    [sprite setTexture:tex];
    [sprite setTextureRect:CGRectMake(0, 0, size.width, size.height)];
    free(buffer);
    return sprite;
}

Then you can set your color, size and opacity as needed. ;)

like image 111
Matjan Avatar answered Sep 28 '22 04:09

Matjan


CCSprite has a color property of type ccColor3B:

- (ccColor3B) color [read, assign]
RGB colors: conforms to CCRGBAProtocol protocol    

Definition at line 145 of file CCSprite.h.

Source: CCSprite reference.

You can easily construct a ccColor3B struct using ccc3():

ccc3(const GLubyte r, const GLubyte g, const GLubyte b)

Reference: ccColor3B reference.

like image 29
Justin Avatar answered Sep 28 '22 02:09

Justin