Take the 2-minute tour ×

has anyone an idea how to convert a UIImage to cocos2d-x CCSprite. My latest attempt was was: 1. Store the UIImage as png on the phone 2. Load the png as a CCSprite

[UIImagePNGRepresentation(photo) writeToFile:imagePath atomically:true];
CCSprite *sprite = CCSprite::spriteWithFile(imagePath);

But this crashed in CCObject retain function

void CCObject::retain(void)
    CCAssert(m_uReference > 0, "reference count should greater than 0");


And I do not understand how Walzer Wangs suggestion works http://cocos2d-x.org/boards/6/topics/3922

CCImage::initWithImageData(void* pData, int nDataLen, ...)
CCTexture2D::initWithImage(CCImage* uiImage);
CCSprite::initWithTexture(CCTexture2D* pTexture);
share|improve this question
add comment

2 Answers

CCSprite* getCCSpriteFromUIImage(UIImage *photo) {
    CCImage *imf =new CCImage();
    NSData *imgData = UIImagePNGRepresentation(photo);
    NSUInteger len = [imgData length];
    memcpy(byteData, [imgData bytes], len);
    CCTexture2D* pTexture = new CCTexture2D();
    CCSprite *sprit = new CCSprite();
    DebugLog("size :%f :%f ",sprit->getContentSize().width , sprit->getContentSize().height);

    return sprit;
share|improve this answer
Hi and welcome to SO. Answering is nice, but we'd like to encourage to you provide some context and explanation : this might help people with similar issues to understand how to solve them. Again, welcome ! –  m_x Feb 28 '13 at 11:38
add comment
up vote 0 down vote accepted

I got the solution for my own Problem. You can't create a CCSprite before the CCDirector is initialized. There are missing some config settings and cocos releases the image right after it is instantiated.

share|improve this answer
add comment

Your Answer


