iPhone Cocos2D - 使用特定图像启动场景

时间:2011-11-11 15:45:03

标签: iphone ios ipad cocos2d-iphone

我想在cocos2d上开始一个新场景,但我想传递图像以用作场景背景本身。

如果是UIImageViews,则相当于

UIImageView *myIV = [[UIImageView alloc] initWithimage: myImage];

是的,myImage是将填满整个myIV的图像。

用cocos2d谈论,

我会使用类似的东西来调用场景,

[[CCDirector sharedDirector] replaceScene:
     [CCTransitionFade transitionWithDuration:0.5f scene:[myScene scene]]];

但如果场景将进入屏幕,我该如何指定图像以便根据图像创建图像(使用图像为bg和图像大小)。

我考虑在myScene上创建一个属性来传递图像,但是这将是无用的,因为init将在设置属性之前运行,并且据我所知,init方法必须使用图像作为参考

2 个答案:

答案 0 :(得分:3)

使用以UIImage为参数的初始化程序扩展“myScene”类:

-(id) initWithUIImage:(UIImage*)image
{
    if ((self = [super init]))
    {
        CCTexture2D* tex = [[[CCTexture2D alloc] initWithImage:image] autorelease];
        CCSprite* bg = [CCSprite spriteWithTexture:tex];
        [self addChild:bg];
        // ...
    }
    return self;
}

+(id) sceneWithUIImage:(UIImage*)image
{
    return [[[self alloc] initWithUIImage:image] autorelease];
}

然后你可以创建这个场景(假设你的“myScene”类被命名为“MySceneClass”:

MySceneClass* myScene = [MySceneClass sceneWithUIImage:image];
id trans = [CCTransitionFade transitionWithDuration:0.5f scene:myScene];
[[CCDirector sharedDirector] replaceScene:trans];

答案 1 :(得分:1)

您总是可以在appDelegate中放置一些方法来设置属性,然后从初始化中获取值?

-(void) setImageToUse:(NSString *)theImageString {
imageToUSe = theImageString;
}

-(int) returnImageToUse {
return imageToUSe;
}

或者只是将字符串保存到nsuserdefaults并再次在init方法中检索它?