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