2012-12-12 67 views
-1

如何顯示圖像從UIImagePickerController到另一個ViewController.xib?UIImagePickerController到另一個ViewController

我有「ViewController1」,在這裏我得到這個代碼:

- (IBAction)goCamera:(id)sender { 


    UIImagePickerController * picker = [[UIImagePickerController alloc] init]; 
    picker.delegate = self; 
    [picker setSourceType:UIImagePickerControllerSourceTypeCamera]; 
    [self presentModalViewController:picker animated:YES]; 
} 


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
    [picker dismissModalViewControllerAnimated:YES]; 
    UIImageView *theimageView = [[UIImageView alloc]init]; 
    theimageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; 

} 

我怎麼能去「ViewController2」,並顯示出拍攝的照片呢?我使用ViewController1拍攝一張照片,並且我想在ViewController2中顯示這張拍攝的照片,我在那裏獲得了一個UIImageView。非常感謝

回答

2

最好的辦法是在您收到圖像後立即將圖像保存在應用程序的文件夾中。

這很重要,因爲它有助於內存管理

您可以放開圖像數據,而不是將它傳遞給應用程序。

我用類似的代碼如下:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

    UIImage *originalImage, *editedImage, *imageToSave; 
    editedImage = (UIImage *) [info objectForKey: 
           UIImagePickerControllerEditedImage]; 
    originalImage = (UIImage *) [info objectForKey: 
           UIImagePickerControllerOriginalImage]; 
    imageToSave = (editedImage!=nil ? editedImage : originalImage); 


    // Check if the image was captured from the camera 
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) { 
     // Save the image to the camera roll 
     UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil); 
    } 

    NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
    NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"]; 

    NSData *data = UIImageJPEGRepresentation(imageToSave, 0.8); 
    BOOL result = [data writeToFile:filepathJPG atomically:YES]; 
    NSLog(@"Saved to %@? %@", filepathJPG, (result? @"YES": @"NO")); 

    [picker dismissModalViewControllerAnimated:YES]; 
} 

然後在您的其他視圖控制器,無論你會希望加載圖像(viewDidLoad中,viewWillAppear中或其他地方)提出:

NSString *docspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString *filepathJPG = [docspath stringByAppendingPathComponent:@"imagefile.jpg"]; 

UIImage *img = [UIImage imageWithContentsOfFile: filepathJPG]; 
if (img != nil) { 
    // assign the image to the imageview, 
    myImageView.image = img; 

    // Optionally adjust the size 
    BOOL adjustToSmallSize = YES; 
    CGRect smallSize = (CGRect){0,0,100,100}; 
    if (adjustToSmallSize) { 
     myImageView.bounds = smallSize; 
    } 

} 
else { 
    NSLog(@"Image hasn't been created"); 
} 

希望有幫助

相關問題