ios 实现拍照与显示在界面上

1、添加权限与描述

2、代码

objectivec 复制代码
#import "ViewController.h"

@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建显示照片的imageView
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 200, 200)];
    [self.view addSubview:self.imageView];
    
    // 创建拍照按钮
    UIButton *takePhotoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [takePhotoButton setTitle:@"拍照" forState:UIControlStateNormal];
    takePhotoButton.frame = CGRectMake(50, 350, 100, 50);
    [takePhotoButton addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:takePhotoButton];
}

- (void)takePhoto {
    // 检查相机是否可用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"相机不可用" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    // 创建 UIImagePickerController
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

// 拍照完成后调用的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
    self.imageView.image = selectedImage;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 用户取消拍照时调用的代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
相关推荐
2501_9159184114 小时前
iOS 框架全解析,原生框架与跨平台框架对比、开发应用打包与 App Store 上架实战经验
android·ios·小程序·https·uni-app·iphone·webview
Everbrilliant8914 小时前
Xcode上编译调试ffmpeg
macos·ffmpeg·xcode·ffmpeg源码编译工具·xcode调试ffmpeg源码·ffmpeg工具环境变量配置
感谢地心引力14 小时前
iOS26 打开开发者模式
windows·macos·ios·iphone·ios26
低调小一16 小时前
iPhone美区账号登录指南:轻松下载ChatGPT应用
ios·chatgpt·iphone
追光天使1 天前
Mac 安装Neo4j教程
macos·neo4j
一勺菠萝丶2 天前
macOS 终端配置全攻略:zsh、bash_profile、zprofile、zshrc 到 nvm 配置的完整科普
macos·bash·策略模式
2501_916007472 天前
前端开发工具都有哪些?常用前端开发工具清单与场景化推荐
android·ios·小程序·https·uni-app·iphone·webview
2501_915909062 天前
iOS 应用上架全流程解析,苹果应用发布步骤、ipa 上传工具、TestFlight 测试与 App Store 审核经验
android·macos·ios·小程序·uni-app·cocoa·iphone
Jouzzy2 天前
【iOS安全】iPhone X iOS 16.7.11 (20H360) Palera1n MacOS版 越狱教程
macos·ios·iphone
ZFJ_张福杰2 天前
【Flutter】GetX最佳实践与避坑指南
android·flutter·ios·getx