简体   繁体   中英

CCSprite with image from URL in cocos2d v3

I'm trying to get Facebook profile image, but I'm not able to transform the data that I get from facebook into a Texture,

 NSData *data = [NSData dataWithContentsOfURL:url];
 UIImage *image = [UIImage imageWithData:data];
 NSLog(@"sprite nao existe");
 //convert UIImage to CCSprite
 **CCTexture *texture = [CCTexture textureWithFile:image];**


 CCSprite *sprite = [CCSprite spriteWithTexture:texture];
 sprite.position = ccp(winWidth*.5, winHeight*.5)

In the line CCTexture *text... I'm getting this warning, which make the simulator stops/crashes:

Incompatible pointer types sending 'UIImage' to parameter of type NSString

This is the message when the simulator stops in the Log

 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'TextureCache: fileimage MUST not be nil'
*** First throw call stack:
CCTexture *texture = [CCTexture textureWithFile:image];

Here image must be a NSString not a UIImage. The reference will tell you that.

Instead use this method:

- (id)initWithCGImage:(CGImageRef)cgImage contentScale:(CGFloat)contentScale

Like so:

CCTexture *texture = [[CCTexture alloc] initWithCGImage:image.CGImage 
                                           contentScale:image.scale];

Try below code to set image in your Sprite

NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
CCSprite *sprite = [CCSprite spriteWithCGImage:image.CGImage key:@"BB"];
sprite.position = ccp(winWidth*.5, winHeight*.5)
[self addChild:sprite];

Yes @LearnCocos2D, you are absolutely right. I have created a category on CCSprite and created a method named

+ (id)spriteWithURL:(NSString*)imageURL defaultSprite:(NSString*)defaultImage;

. It simply creates a CCSprite from the defaultImage and if download of image with the imageURL completes, it automatically sets the texture of CCSprite from the downloaded image. You can find out the whole project from GitHub . Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM