Search code examples
cocos2d-iphonescreenshotcgrect

How to take screenshot of a user defined rectangular area in cocos2d


I need to take the screenshot in my cocos2d application. I've searched a lot, even in stack overflow. Then I found the following code:

+(UIImage*) screenshotWithStartNode:(CCNode*)stNode
{
    [CCDirector sharedDirector].nextDeltaTimeZero = YES;

    CGSize winSize = [[CCDirector sharedDirector] winSize];
    CCRenderTexture* renTxture = 
    [CCRenderTexture renderTextureWithWidth:winSize.width 
                                 height:winSize.height];
    [renTxture begin];
    [stNode visit];
    [renTxture end];

    return [renTxture getUIImage];
}

Now,

Problem: The above code gives me the entire screenshot. But I am in need of the screenshot of a custom are, such as, within a CGRect(50,50,100,200).

Can anyone please help me..? Thanks...


Solution

  • Wow... found out what I need. I've changed the above method like:

    -(UIImage*) screenshotWithStartNode:(CCNode*)startNode
    {
        [CCDirector sharedDirector].nextDeltaTimeZero = YES;
    
        CGSize winSize = [CCDirector sharedDirector].winSize;
        CCRenderTexture* rtx =
        [CCRenderTexture renderTextureWithWidth:winSize.width
                                         height:winSize.height];
    
        [rtx begin];
        [startNode visit];
        [rtx end];
    
        UIImage *tempImage = [rtx getUIImage];
        CGRect imageBoundary = CGRectMake(100, 100, 300, 300);
    
        UIGraphicsBeginImageContext(imageBoundary.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // translated rectangle for drawing sub image
        CGRect drawRect = CGRectMake(-imageBoundary.origin.x, -imageBoundary.origin.y, tempImage.size.width, tempImage.size.height);
    
        // clip to the bounds of the image context
        CGContextClipToRect(context, CGRectMake(0, 0, imageBoundary.size.width, imageBoundary.size.height));
    
        // draw image
        [tempImage drawInRect:drawRect];
    
        // grab image
        UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return subImage;
    
    }