我正在尝试从相机获取图像并将拍摄的图像放入UIImageView(不使用相机胶卷 - 直接从相机到UIImageView)。几周来我一直努力尝试解决这个问题但没有成功。有谁知道为什么这不起作用?
仅供参考,我一直在做什么?
如果一个聪明的程序员可以帮我解决这个问题,我将不胜感激。我觉得我做的一切都是我读他人告诉我的事情。任何代码类型的更正都将非常有用。谢谢!
- (IBAction)cameraButtonPushed:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == NO) {
//todo if device has no camera
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable To Locate Camera" message:@"No Camera found." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
else {
UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
cameraUI.delegate = delegate;
cameraUI.allowsEditing = YES;
cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
cameraUI.mediaTypes =
[UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
[self presentViewController:cameraUI animated:YES completion:^{
}];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
UIImage *takenImage = [info valueForKey:UIImagePickerControllerEditedImage];
[self.navigationController pushViewController:self animated:YES];
image = [[UIImageView alloc] initWithImage:takenImage];
}];
}
答案 0 :(得分:3)
试试这个:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES
completion:^{
UIImage *takenImage = [info valueForKey:UIImagePickerControllerEditedImage];
image = [[UIImageView alloc] initWithImage:takenImage];
[self.view addSubview:image];
//or if object is connected properly via IB then simply
//[image setImage:takenImage];
}];
}
根据@DouglasFerreira的敏锐观察
cameraUI.delegate = delegate;
应该是
cameraUI.delegate = self;
答案 1 :(得分:2)
如果image
是IBOutlet
,则您不必初始化它:它将由您的故事板或您的XIB完成。尝试设置图像:
[image setImage: takenImage];
答案 2 :(得分:0)
您可以使用以下方法完成任务,但请确保将视图控制器委托给UIImagePickerControllerDelegate,UINavigationControllerDelegate
- (IBAction)takePhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}