John Biesnecker
John Biesnecker

Reputation: 3812

Drawing antialiased circle in a CCRenderTexture

I'm new to cocos2d / OpenGLES, and I'm running into a problem for which I cannot find a solution. Basically, I want to draw an antialiased circle in a CCRenderTexture, and then use that texture on multiple sprites. Everything but the antialiasing part is simple, but I'm stuck and can't figure out where to go next.

The code I have now is:

int textureSize = 64;
CCRenderTexture *rt = [CCRenderTexture renderTextureWithWidth:textureSize height:textureSize];
[rt beginWithClear:spriteColor.r g:spriteColor.g b:spriteColor.b a:0.0f];

ccDrawColor4F(spriteColor.r, spriteColor.g, spriteColor.b, spriteColor.a);
ccDrawCircle(CGPointMake(textureSize / 2.0f, textureSize / 2.0f), textureSize / 2.0f, 0.0f, 360, false);

[rt end];

That results in a jagged mess, however, and I can't figure out where to go from here. I've seen examples online of using points to draw smooth circles, but that doesn't seem to work in OpenGLES 2.0.

Performance isn't much of an issue as I'm drawing to the texture once and reusing the texture over and over.

Upvotes: 2

Views: 1669

Answers (1)

Ben Trengrove
Ben Trengrove

Reputation: 8749

Create your circle texture in Core Graphics and add it to the Texture Cache as a CGImage. Core Graphics uses antialiasing automatically. The circle will look like this.

Circle

Sample Code:

//Setup Core Graphics
CGSize circleSize = CGSizeMake(100, 100);
CGPoint circlePosition = ccp(50, 50);
UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
CGContextRef context = UIGraphicsGetCurrentContext();

//Add the circle to the context and draw it.
CGContextAddArc(context, circlePosition.x, circlePosition.y , circleSize.width/2, 0,2*M_PI,1);
CGContextDrawPath(context,kCGPathStroke);

//Get an image so we can store it in the Texture Cache
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//Add the image to the texture cache
[[CCTextureCache sharedTextureCache] addCGImage:[img CGImage] forKey:@"circleKey"];

You can then make a sprite using

CCSprite *circle = [CCSprite spriteWithTexture:[[CCTextureCache sharedTextureCache] textureForKey:@"circleKey"]];

Upvotes: 9

Related Questions