cocos2d-x convert UIImage to CCSprite

2019-08-05 08:34发布

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");

    ++m_uReference;
}

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

3条回答
Emotional °昔
2楼-- · 2019-08-05 09:00

Save uiimage to documents directory first

now get it using getWritablePath

Texture2D* newTexture2D = new Texture2D();
Image* JpgImage     = new Image();

JpgImage->initWithImageFile("your image path.jpg");
newTexture2D->initWithData(JpgImage->getData(),JpgImage->getDataLen(),Texture2D::PixelFormat::RGB888,JpgImage->getWidth(),JpgImage->getHeight(),Size(JpgImage->getWidth(),JpgImage->getHeight()));
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-05 09:06

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.

查看更多
做个烂人
4楼-- · 2019-08-05 09:11
CCSprite* getCCSpriteFromUIImage(UIImage *photo) {
    CCImage *imf =new CCImage();
    NSData *imgData = UIImagePNGRepresentation(photo);
    NSUInteger len = [imgData length];
    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [imgData bytes], len);
    imf->initWithImageData(byteData,imgData.length);
    imf->autorelease();
    CCTexture2D* pTexture = new CCTexture2D();
    pTexture->initWithImage(imf);
    pTexture->autorelease();
    CCSprite *sprit = new CCSprite();
    sprit->createWithTexture(pTexture);
    sprit->autorelease();
    DebugLog("size :%f :%f ",sprit->getContentSize().width , sprit->getContentSize().height);

    return sprit;
}
查看更多
登录 后发表回答