How to save CCSprite as PNG

I created CCSprite and add it to the main view. Then I want to see the image of the sprite, so I saved it in PNG But many of them are not saved correctly. Only show white background. I can’t know the reason, and also found some articles through Google, but they didn’t help me at all. How can i solve this?

CCSprite *sprite = [[CCSprite spriteWithFile:[NSString stringWithUTF8String:name] rect:CGRectMake(startx, starty, w, h)] retain];

float drawX = x, drawY = y; 

CGSize size = [sprite contentSize];

int nWidth = size.width;
int nHeight = size.height;
nWidth *= scale;
nHeight *= scale;
drawX = drawX + nWidth/2;
drawY = drawY - nHeight/2;

ConvertCoordf(&drawX, &drawY);
drawY -= nHeight;
[sprite setScale:scale];
[sprite setPosition:ccp(drawX, drawY)];
[_mainLayer addChild:sprite];

CCRenderTexture* render = [CCRenderTexture renderTextureWithWidth:sprite.contentSize.width height:sprite.contentSize.height];    
[render begin];
[sprite visit];
[render end];    
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString  *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"new%d.png",i]];
i++;
[render saveBuffer:pngPath format:kCCImageFormatPNG];

[sprite release];
+5
source share

All Articles