Duck
Duck

Reputation: 35953

iPhone Cocos2D - Starting a scene with a specific image

I would like to start a new scene on cocos2d, but I want to pass the image to be used as the scene background itself.

If it was with UIImageViews, it would be the equivalent of

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

that, is, myImage is the image that will fill the entire myIV.

Talking in terms of cocos2d,

I would call the scene using something like this,

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

but if the scene will enter the screen, how can I specify the image so it is created based on the image (using the image as bg and at the size of the image).

I thought about creating a property on myScene to pass the image, but this will be useless, as the init will run before the property can be set and as far as I realize, the init method has to run using the image as reference.

Upvotes: 1

Views: 334

Answers (2)

CodeSmile
CodeSmile

Reputation: 64477

Extend your "myScene" class with an initializer that takes the UIImage as an argument:

-(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];
}

Then you can create this scene (this assumes that your "myScene" class is named "MySceneClass":

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

Upvotes: 3

ader
ader

Reputation: 5393

You could always put some methods in your appDelegate to set a property and then get the value from within your init?

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

-(int) returnImageToUse {
return imageToUSe;
}

or simply save the string to nsuserdefaults and again retrieve it in the init method?

Upvotes: 1

Related Questions