我想在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方法必须使用图像作为参考运行。
用一个初始化器扩展你的"myScene"类,该初始化器将UIImage作为参数:
-(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];
你总是可以在你的appDelegate中放置一些方法来设置属性,然后从你的init中获取值?
-(void) setImageToUse:(NSString *)theImageString {
imageToUSe = theImageString;
}
-(int) returnImageToUse {
return imageToUSe;
}
或者简单地将字符串保存到nsuserdefaults并再次在init方法中检索它?