在cocos2dx中对Sprite的UIImage?

时间:2015-02-27 05:50:57

标签: uiimage ccsprite cocos2d-x-3.0

首先,我从文档目录中的URL保存图像:

NSURL *imageURL = [NSURL URLWithString:userImage];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"image name.png"];

[UIImagePNGRepresentation(image) writeToFile:savedImagePath atomically:YES];

然后我想在cpp中检索这个图像为Sprite:

std::string writablePath2 = CCFileUtils::getInstance()->getWritablePath();
writablePath2.append("your saved image.png");
Rect rect2 = Rect(visibleSize.width/2 - 200, visibleSize.height/2 -200 , 500, 500 );
Sprite *screen_shot = Sprite::create(writablePath2,rect2);
screen_shot->setPosition(visibleSize.width/2 ,origin.y + visibleSize.height/2 - 100);
this->addChild(screen_shot,2);

但它正在显示黑色精灵。

1 个答案:

答案 0 :(得分:0)

1)从文件路径

创建Texture2D

2)从Texture2D

创建Sprite

这是代码

std::string imagPath = CCFileUtils::getInstance()->getWritablePath();
imagPath.append("your image name.png");

Texture2D* objTexture2D = new Texture2D();
Image* image = new Image();

JpgImage->initWithImageFile(imagPath);
objTexture2D->initWithData(image->getData(),image->getDataLen(),Texture2D::PixelFormat::RGB888,image->getWidth(),image->getHeight(),Size(image->getWidth(),image->getHeight()));

Sprite *spr = Sprite::createWithTexture(objTexture2D);
spr->setPosition(origin.x + visibleSize.width/2 , visibleSize.height/2);
this->addChild(spr,2);

在这里你去....