1

Is there a way one could add a border around a plain color sprite without having to create another sprite?

Here the code to create the plain colored rectangular sprite. Thanks goes to Mat Cegiela for sharing it on SO (https://stackoverflow.com/a/14609459/1097106).:

-(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;
}

This works great as it doesn't use any image files.

To add a border one could create two plain colored sprites using the above method, one slightly smaller and add the smaller one as a child to the parent sprite, but is there a way one could do it more elegantly?

I tried (https://stackoverflow.com/a/10903183/1097106) -- thanks Morion for sharing it:

CGSize selfSize = [self contentSize];
float selfHeight = selfSize.height;
float selfWidth = selfSize.width;
CGPoint vertices[4] = {ccp(0.f, 0.f), ccp(0.f, selfHeight), ccp(selfWidth, selfHeight), ccp(selfWidth, 0.f)};
ccDrawPoly(vertices, 4, YES);

in the sprite's -(void)draw without any positive result. It doesn't show the sprite at all when adding this code to -(void)draw.

Edit: Turns out the problem was a missing [super draw]; inside -(void)draw. Adding it will make it work.

Here the implementation of -(void)draw that will allow for borders around a plain color rectangular sprite (it also defines a custom color):

-(void)draw
{
    [super draw];

    CGSize selfSize = [self contentSize];
    float selfHeight = selfSize.height;
    float selfWidth = selfSize.width;
    CGPoint vertices[4] = {ccp(0.f, 0.f), ccp(0.f, selfHeight), ccp(selfWidth, selfHeight), ccp(selfWidth, 0.f)};
    ccDrawColor4B(120, 120, 120, 255);
    ccDrawPoly(vertices, 4, YES);
}
Community
  • 1
  • 1
schmittsfn
  • 1,412
  • 18
  • 40
  • I guess you could create the buffer you are using for instantiating the CCTexture2D with the border itself. This would mean to use the border color for those points that were at the border position. I don't know how you would do that, but it should be possible. – Ricard Pérez del Campo Mar 06 '13 at 14:17
  • @Ricard That would probably be more efficient than handling it in `-(void)draw`. I've been doing some research on how one could possibly do it, but couldn't find a solution so far. – schmittsfn Mar 06 '13 at 16:37
  • try CCDrawNode if you're using cocos2d 2.0/2.1 – CodeSmile Mar 06 '13 at 19:16

0 Answers0