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
相关推荐
__WanG1 小时前
Mac 本地部署 OMLX + 通义千问 Qwen3.5-27B 保姆级教程
macos
节点小宝2 小时前
一站式部署:支持Windows、macOS、Linux三端的统一方案
linux·运维·macos
呆萌小新@渊洁4 小时前
音频识别入门内容
macos·音视频·xcode
觉醒程序员7 小时前
Mac电脑硬盘扩容后,如何重装git,node更干净
macos
Digitally8 小时前
iPhone 卡在恢复模式:如何修复(分步指南)
ios·iphone
LAM LAB9 小时前
【Mac】修改改 command 和 alt 键位映射
macos
vx-bot5556669 小时前
企业微信ipad协议的协议状态机与生命周期管理
ios·企业微信·ipad
ITKEY_9 小时前
macOS通过命令行启动iOS模拟器
macos·ios
00后程序员张9 小时前
iPhone 无需越狱文件管理 使用Keymob查看导出文件
android·ios·小程序·https·uni-app·iphone·webview
OneCrab10 小时前
Iphone漏洞利用工具包 Coruna DarkSword
ios·cocoa·iphone