2014-09-06 64 views
1

我爲iPhone製作了一款應用程序,它是Flappy Bird的靈感來源。這個應用程序只是爲了讓我可以學習應用程序製作背後的編程,並希望儘快製作出更原創和先進的應用程序。如何在iOS 5中保存和加載Xcode 5中的圖像?

該應用程序可以加載從您的照片庫,或從您的iPhone相機拍攝的照片。我用這個代碼:

- (IBAction)didTapPhoto:(UITapGestureRecognizer *)sender { 
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take a Photo", @"Use Photo Library", nil]; 

    [actionSheet showInView:self.view]; 
} 

-(void) pickPhotoFromLibrary { 
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

    [self.navigationController presentViewController:self.imagePicker animated:YES completion:nil]; 
} 

-(void) takePhotoWithCamera { 
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; 

    [self.navigationController presentViewController:self.imagePicker animated:YES completion:nil]; 
} 

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 
    if (buttonIndex == actionSheet.cancelButtonIndex)return; 

    switch (buttonIndex) { 
     case 0: 
      [self takePhotoWithCamera]; 
      break; 
     case 1: 
      [self pickPhotoFromLibrary]; 
     default: 
      break; 
    } 
} 

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
    [picker dismissViewControllerAnimated:YES completion:nil]; 

    UIImage *image = info[UIImagePickerControllerOriginalImage]; 

    self.imageView.image = image; 
} 

的問題是:我如何保存這在ImageView的加載圖片,然後在另一個視圖控制器加載它?

我想讓用戶拍一張照片,然後用自己作爲飛揚的小鳥。我已經制作了Flappy Bird球場,並習慣了不同的飛鳥。

唯一的問題是,我希望它可以將用戶選擇的圖片保存爲.png文件,就像它保存在支持文件中一樣。圖片可以保存爲默認值,例如@「image1」,在另一個ViewController中,您可以設置ImageView加載@「image1」。

回答

0

保存圖像到iPhone本地文件:

NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString *imageName = [imagePath stringByAppendingPathComponent:@"MainImage.jpg"]; 
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0); 
BOOL result = [imageData writeToFile:imageName atomically:YES]; 
NSLog(@"Saved to %@? %@", imageName, (result? @"YES": @"NO")); 

加載保存的圖像:

NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString *imageName = [imagePath stringByAppendingPathComponent:@"MainImage.jpg"]; 
UIImage *image = [UIImage imageWithContentsOfFile:imageName]; 
+0

謝謝! 對不起,但我是新手。此代碼中是否有任何內容需要更改或自定義以適合我的代碼? – 2014-09-06 18:18:49