我想将相机拍摄的照片显示到另一个UIViewController中。 我试试这个代码片段,但我认为我做错了,因为照片没有显示在第二个视图中:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
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 dismissViewControllerAnimated:YES completion:nil];
mainViewController *main = [[mainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
main.myImag.image = imageToSave;
}
更新:
我改为使用故事板作为第二个视图:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:@"idmain"]){
mainViewController *main = (mainViewController *)[segue destinationViewController];
main.myImag.image = imageToSave;
}
}
在mainViewController中:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
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,
myImag.image = img;
}
else {
NSLog(@"Image hasn't been created");
}
}
但是当我按下选择时,第二个视图控制器不会出现。
答案 0 :(得分:1)
您正在将照片保存在文档目录中,因此您必须从文档目录
访问它们试
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:imagefile.jpg];
UIImage* image = [UIImage imageWithContentsOfFile:path];
通过此代码,您可以从文档目录中获取图像。
答案 1 :(得分:0)
...假设您的imageToSave
UIImage对象有效(首先),
而不是
svc.myImag.image = imageToSave;
这样做
svc.currentImage = imageToSave;
//where currentImage is a UIImage synthesized property in mainViewController class
然后在mainViewController类的-viewDidLoad
或-viewWillAppear
中
将currentImage
设置到myImag
UIImageView对象上。
简单地:
//mainViewController
- (void)viewWillAppear {
...
myImag.image = currentImage;
}
原因?? ...
UIViewController
的{{3}}方法的iOS文档声明:
... 您指定的nib文件不会立即加载。它是在第一次访问视图控制器的视图时加载的。如果要在加载nib文件后执行其他初始化,请覆盖
viewDidLoad
方法并在那里执行任务。 ...
看到类似的: -initWithNibName:bundle: