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
相关推荐
木有会21 分钟前
【mac】终端左边太长处理,自定义显示名称(terminal路径显示特别长)
macos
_im.m.z1 小时前
Mac配置和启动 Tomcat
java·macos·tomcat·ssm框架
丁总学Java1 小时前
在 Mac(ARM 架构)上安装 JDK 8 环境
arm开发·macos·架构
koko爱英语1 小时前
Jmeter测试工具的安装和使用,mac版本,jmeter版本5.2.1
测试工具·jmeter·macos
菜鸟小贤贤1 小时前
pyhton+yaml+pytest+allure框架封装-全局变量渲染
python·macos·pytest·接口自动化·jinja2
豪冷啊5 小时前
Xcode15(iOS17.4)打包的项目在 iOS12 系统上启动崩溃
macos·objective-c·cocoa
菜鸟小贤贤12 小时前
python+pytest+allure利用fix实现接口关联
python·macos·自动化·pytest
csdn_金手指12 小时前
Mac 系统上控制台常用性能查看命令
java·开发语言·macos
csdn_金手指16 小时前
MacOS系统上Jmeter 录制脚本遇到的证书坑位
jmeter·macos
zolty16 小时前
MAC C语言 Helloword
c语言·开发语言·macos