我正在使用UIImagePickerController讓用戶在我的Cocos2D遊戲中選擇背景。它在你第一次使用它的時候有效,但是如果你試圖再次改變背景,那麼選擇器會顯示出來,但是當你選擇圖片時,背景將保持不變。UIImagePickerController只能工作一次
這是我的代碼:
- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSArray *TouchesA = touches.allObjects;
for (int i = 0; i < TouchesA.count; i++) {
CGPoint touchLocation = [self convertTouchToNodeSpace:[TouchesA objectAtIndex:i]];
CGRect rect = CGRectMake(touchLocation.x, touchLocation.y, 1, 1);
if(CGRectIntersectsRect(rect, infoButton.boundingBox))
{
[self pickPhoto:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
}
}
}
-(void)pickPhoto:(UIImagePickerControllerSourceType)sourceType{
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.sourceType = sourceType;
//picker.wantsFullScreenLayout = YES;
//[picker presentModalViewController:picker animated:YES];
[[[CCDirector sharedDirector] openGLView] addSubview:picker.view];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];
[picker.view removeFromSuperview];
[picker release];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info{
newImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[picker dismissModalViewControllerAnimated:YES];
[picker.view removeFromSuperview];
[picker release];
CCSprite *imageFromPicker = [CCSprite spriteWithCGImage:newImage.CGImage key:@"ImageFromPicker"];
Background = imageFromPicker;
int SSw = [CCDirector sharedDirector].winSize.width;
int SSh = [CCDirector sharedDirector].winSize.height;
Background.position = ccp(SSw/2, SSh/2);
Background.scaleX = SSw/Background.textureRect.size.width;
Background.scaleY = SSh/Background.textureRect.size.height;
[[self children] removeObjectAtIndex: 0];
[[self children] insertObject:Background atIndex:0];
}
我怎樣才能解決這個問題?
編輯:
@interface HelloWorldLayer : CCLayer <UIImagePickerControllerDelegate,
UINavigationControllerDelegate>
{
CCSprite *infoButton;
CCSprite *Background;
UIImage *newImage;
}
-(id) init
{
if((self=[super init])) {
self.isTouchEnabled = true;
[[CCDirector sharedDirector].openGLView setMultipleTouchEnabled:YES];
int SSw = [CCDirector sharedDirector].winSize.width;
int SSh = [CCDirector sharedDirector].winSize.height;
Background = [CCSprite spriteWithFile:@"B.jpg"];
Background.position = ccp(SSw/2, SSh/2);
Background.scaleX = SSw/Background.textureRect.size.width;
Background.scaleY = SSh/Background.textureRect.size.height;
infoButton = [CCSprite spriteWithFile:@"info.png"];
infoButton.position = ccp(SSw - 15, 15);
[self addChild:Background];
[self addChild:infoButton];
[self schedule:@selector(nextFrame:)];
}
return self;
}
當我用這段代碼選擇圖片時,應用程序崩潰。 – Bananable
對不起,你可以編輯你的問題與你如何實例化和使用'背景'?我猜想你是如何這樣做的,這可能是導致崩潰的原因(例如,當你第一次使用它時,你可能不會保留'Background')。謝謝! – donkim
那裏。編輯的頂部來自我的圖層的標題,而init方法來自我的圖層的.m。 – Bananable