How to Convert a CCSprite image to UIImage?

2019-07-16 21:52发布

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?

4条回答
我命由我不由天
2楼-- · 2019-07-16 22:02

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楼-- · 2019-07-16 22:02

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

查看更多
我命由我不由天
4楼-- · 2019-07-16 22:12

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]
查看更多
ゆ 、 Hurt°
5楼-- · 2019-07-16 22:19

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

查看更多
登录 后发表回答