将UIImage添加到CCSprite?

时间:2011-11-11 05:15:22

标签: ios image api cocos2d-iphone

我不知道这是不是很愚蠢,但我现在已经在这个问题上抓了大约一两个小时。

我从NSData获取NSUserDefaults个对象,然后将其转换为UIImage。现在我如何将CCSprite的图像设置为我的UIImage?

spriteWithFile不起作用,因为它需要NSString。我正在寻找一个参数为UIImage的API。这可能吗?

有什么想法吗?

Edit1 :这是怎么回事?

UIImage *image = [UIImage imageWithData:(NSData*)obj];
sprite = [CCSprite spriteWithCGImage:image.CGImage key:@"mainSprite"];

2 个答案:

答案 0 :(得分:10)

试试这个:

CCTexture2D *tex = [[[CCTexture2D alloc] initWithImage:uiImage] autorelease];
CCSprite *sprite = [CCSprite spriteWithTexture:tex];

uiImage是一个UIImage对象。

答案 1 :(得分:1)

这种方法对我来说非常有用......

 -(CCSprite*)spriteFromDiskFileName:(NSString*)fileName
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES);
        NSString *directoryPath = [paths objectAtIndex:0] ;
        NSData *imageData = [[NSData alloc]initWithContentsOfFile:[directoryPath stringByAppendingPathComponent:fileName]];

        UIImage *spriteImage = [UIImage imageWithData:imageData];

        if (spriteImage) {
            printf("\nUIImage created from disk image \n");
        }
        else
        {
            printf("\nUIImage creation failed from disk image \n");
        }

        CCTexture2D *texture = [[CCTexture2D alloc] initWithCGImage:spriteImage.CGImage resolutionType:kCCResolutionUnknown];
        return [CCSprite spriteWithTexture:texture];
    }