如何将CCSpriteBatchNode转换为UIImage?

时间:2012-07-11 06:06:56

标签: cocos2d-iphone uiimage ccsprite

我想将CCSpriteBatchNode转换为UIImage,有可能这样做吗?我知道可以将CCSprite转换为UIImage,但是当我使用CCSpriteBatchNode进行尝试时,它会崩溃:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'CCSpriteBatchNode should NOT be root node'

谢谢!

以下是将CCSprite转换为UIImage的代码。

+ (UIImage *)renderUIImageFromSprite:(CCSprite *)sprite {
    CCRenderTexture *renderer = [CCRenderTexture renderTextureWithWidth:sprite.contentSize.width; height:sprite.contentSize.height;];
    [renderer begin];
    [sprite visit];
    [renderer end];
    return [renderer getUIImageFromBuffer];
}

编辑: 这是工作代码。

+ (UIImage *)renderUIImageFromCCLabelBMFont:(CCLabelBMFont *)bmfont {
    GLProgram *program = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor];
    glUseProgram(program->program_);

    int textureWidth = bmfont.contentSize.width;
    int textureHeight = bmfont.contentSize.height;

    CCRenderTexture *renderer = [CCRenderTexture renderTextureWithWidth:textureWidth height:textureHeight];
    bmfont.anchorPoint = ccp(0.0, 0.0);

    CCNode *node = [CCNode node];
    [node addChild:bmfont];

    [renderer begin];
    [node visit];
    [renderer end];

    return [renderer getUIImageFromBuffer];
}

1 个答案:

答案 0 :(得分:0)

我自己需要这个。这是ARC代码,并设置为CCLabelBMFont的类别。

CCLabelBMFont + UIImage.h

@interface CCLabelBMFont (UIImage)

- (UIImage *)image;

@end

CCLabelBMFont + UIImage.m

@implementation CCLabelBMFont (UIImage)

- (UIImage *)image
{
    CCGLProgram *program = [[CCShaderCache sharedShaderCache] programForKey:kCCShader_PositionTextureColor];
    glUseProgram(program->program_);

    CCRenderTexture *renderer = [[CCRenderTexture alloc] initWithWidth:(int)self.contentSize.width
                                                                height:(int)self.contentSize.height
                                                           pixelFormat:kCCTexture2DPixelFormat_RGBA8888];

    CCLabelBMFont *labelBMFont = [[CCLabelBMFont alloc] initWithString:string_
                                                               fntFile:fntFile_
                                                                 width:width_
                                                             alignment:alignment_
                                                           imageOffset:imageOffset_];

    labelBMFont.anchorPoint = ccp(0.0, 0.0);

    CCNode *node = [CCNode node];
    [node addChild:labelBMFont];

    [renderer begin];
    [node visit];
    [renderer end];

    return [renderer getUIImage];
}

@end