cocos2d-x将UIImage转换为CCSprite

时间:2012-06-28 16:38:50

标签: cocos2d-iphone uiimage ccsprite cocos2d-x

有人知道如何将UIImage转换为cocos2d-x CCSprite。 我最近的尝试是: 1.将UIImage作为png存储在手机上 2.将png作为CCSprite加载

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

但是这在CCObject保留函数中崩溃了

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

    ++m_uReference;
}

我不明白Walzer Wangs的建议是如何运作的 http://cocos2d-x.org/boards/6/topics/3922

CCImage::initWithImageData(void* pData, int nDataLen, ...)
CCTexture2D::initWithImage(CCImage* uiImage);
CCSprite::initWithTexture(CCTexture2D* pTexture);

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我为自己的问题找到了解决方案。在CCDirector初始化之前,您无法创建CCSprite。缺少一些配置设置,cocos在实例化后立即释放图像。

答案 2 :(得分:0)

首先将uiimage保存到文档目录

现在使用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()));