cocos2d-x convert UIImage to CCSprite

女生的网名这么多〃 提交于 2019-12-13 00:41:44

问题


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

回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/11249168/cocos2d-x-convert-uiimage-to-ccsprite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!