How to Convert a CCSprite image to UIImage?

2019-07-16 21:55发布

问题:

As the title, I have mentioned the code below

CCSprite *sprite = (CCSprite *)node;
CCTexture2D *texture2d = [sprite texture];

How can I get a UIImage *p from sprite?

回答1:

In your case just add next methood into your class:

 - (UIImage *) imageFromSprite :(CCSprite *)sprite
{
    int tx = sprite.contentSize.width;
    int ty = sprite.contentSize.height;

    CCRenderTexture *renderer   = [CCRenderTexture renderTextureWithWidth:tx height:ty];

    sprite.anchorPoint  = CGPointZero;

    [renderer begin];
    [sprite visit];
    [renderer end];

    return [renderer getUIImage];
}

how to use:

CCSprite *sprite = (CCSprite *)node;
UIImage *p = [self imageFromSprite:sprite]


回答2:

uhh...

I think this is a better to way. Add this as a category on CCNode.

-(UIImage*)image {
    CCRenderTexture* renderer = [CCRenderTexture renderTextureWithWidth:self.contentSize.width height:self.contentSize.height];

    const CGPoint ANCHORBEFORE = self.anchorPoint;
    self.anchorPoint = CGPointZero;

    [renderer begin];
    [self visit];
    [renderer end];
    self.anchorPoint = ANCHORBEFORE;

    return [renderer getUIImage];
}


回答3:

If you are using cocos2d 2.x, render sprite into CCRenderTexture and call getUIImage method of that render texture.



回答4:

By looking at the source code of both CCSprite and CCTexture2D you can see that the image is used only for creating the texture data and the image object is not kept but temporarily used.

CCTexture2D source :

http://code.google.com/p/cocos2d-iphone/source/browse/trunk/cocos2d/CCTexture2D.m?r=1882

CCSprite source :

http://code.google.com/p/cocos2d-iphone/source/browse/trunk/cocos2d/CCSprite.m?r=1747

Look in the init methods that use CGImageRef