Monday, August 23, 2010

iPhone Cocos2d: Use UIView as background of Cocos2d

This came from a blog called "Not Now Nigel", unfortunately it was removed. I'm salvaging this helpful code from there.

Using a hello world cocos2d template, add the following property to your ____AppDelegate.h:

UIView *overlay;


@property (nonatomic, retain) UIView *overlay;



in the ____AppDelegate.m, synthesize the overlay:

@synthesize overlay;


then replace the contents of:

- (void) applicationDidFinishLaunching:(UIApplication*)application

{

window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

if(![CCDirector setDirectorType:kCCDirectorTypeDisplayLink])

[CCDirector setDirectorType:kCCDirectorTypeNSTimer];

CCDirector *director = [CCDirector sharedDirector];

[director setDeviceOrientation:kCCDeviceOrientationPortrait];

[director setDisplayFPS:YES];

[director setAnimationInterval:1.0/60];

EAGLView *glView = [EAGLView viewWithFrame:[[UIScreen mainScreen] bounds] pixelFormat:kEAGLColorFormatRGBA8 depthFormat:0 preserveBackbuffer:NO];

[director setOpenGLView:glView];

[glView setMultipleTouchEnabled:YES];

glView.opaque = NO;

glClearColor(0.0f,0.0f,0.0f,0.0f);

glClear(GL_COLOR_BUFFER_BIT);

overlay = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

overlay.opaque = YES;

overlay.backgroundColor = [UIColor blackColor];

[overlay addSubview: glView];

[window addSubview:overlay];

[window makeKeyAndVisible];

// Sets landscape mode

// [director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];

// Turn on display FPS

// [director setDisplayFPS:YES];

[CCTexture2D setDefaultAlphaPixelFormat: kTexture2DPixelFormat_RGBA8888];

[director runWithScene: [HelloWorld scene]];

}


In your scene.m, just initialize your UIView (or view controller) then insert the subview as the back-most subview for overlay. For example:


MyNewController *cont = [[MyNewController alloc] init];

cont.wantsFullScreenLayout = YES;

MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

[delegate.overlay insertSubview:cont.view belowSubview:[[CCDirector sharedDirector] openGLView]];



The glView for cocos2d should not be transparent with the UIView you just placed in the background.

1 Comments:

At Thu Sep 29, 06:45:00 PM GMT+8, Blogger scolas said...

You saved my life! :)

After 4 hour searching how to make EAGLEView transparent i found your post and it solved everything!!

Really thanx!!

 

Post a Comment

<< Home