如何在cocos2d中截取用户定义的矩形区域的屏幕截图

时间:2013-11-02 18:05:59

标签: cocos2d-iphone screenshot cgrect

我需要在我的cocos2d应用程序中截取屏幕截图。我搜索了很多,即使在堆栈溢出。然后我找到了以下代码:

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

现在,

问题:以上代码为我提供了完整的屏幕截图。但我需要自定义屏幕截图,例如CGRect(50,50,100,200)

任何人都可以帮助我..?感谢...

1 个答案:

答案 0 :(得分:2)

哇...发现了我需要的东西。我改变了上面的方法,如:

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

}