2012-12-12 66 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"); 
} 

希望有帮助

相关问题