开发者

Cocos2d: Solid color rectangular sprite?

I must be missing something!

I want to cr开发者_JAVA技巧eate 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!


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. ;)


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.


I found answer at cocos2d cookbook. The following code is derived from that book's chap 1, which is free for preview.

-(CCSprite *) rectangleSpriteWithSize:(CGSize)cgsize color:(ccColor3B) c
{
    CCSprite *sg = [CCSprite spriteWithFile:@"blank.png"];  
    [sg setTextureRect:CGRectMake( 0, 0, cgsize.width, cgsize.height)];
    sg.color = c;   
    return sg;  
}

Yes, this still requires an external image file. But with this 1x1 tiny 'blank.png', you can generate solid-color rectangle sprites with arbitrary size and color.


I never got CCSprite to work like that. I just use CCLayerColor.

CCLayerColor* layercolorHalftransparentred = [CCLayerColor layerWithColor:ccc4(255, 0, 0, 128)];


For anyone stumbling upon this question (like me); the code from Matjan doesn't seem to work anymore on cocos 2d 3.x. See below for an altered version that works for me:

+ (CCSprite*)blankSpriteWithSize:(CGSize)size
{
    GLubyte *buffer = malloc(sizeof(GLubyte)*4);
    for (int i=0;i<4;i++) {buffer[i]=255;}
    CCTexture *tex = [[CCTexture alloc] initWithData:buffer pixelFormat:CCTexturePixelFormat_RGBA8888 pixelsWide:1 pixelsHigh:1 contentSizeInPixels:size contentScale:1];
    CCSprite *sprite = [CCSprite spriteWithTexture:tex rect:CGRectMake(0,0,size.width,size.height)];
    free(buffer);
    return sprite;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜