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
相关推荐
Benny的老巢7 小时前
Mac上用XAMPP搭建局域网可访问的开发环境,让局域网内其他设备通过域名访问
nginx·macos·apache·xampp·php开发环境
2501_9418814015 小时前
在墨西哥城复杂流量环境下构建高稳定性API网关的架构设计与实现实践分享
macos·golang·xcode
wadesir15 小时前
macOS Sequoia与macOS Tahoe全面对比:功能、性能与升级教程(新手入门指南)
macos
茅根竹蔗水__15 小时前
iOS应用(App)生命周期、视图控制器(UIViewController)生命周期和视图(UIView)生命周期
ios
FreeBuf_18 小时前
新型TCC绕过漏洞:macOS面临自动化攻击风险
macos·自动化·策略模式
Alice19 小时前
Remote control Mac ios
macos
huaiyanchen19 小时前
mac Navicat 下载及安装
macos
毛发浓密的女猴子19 小时前
SSE Connect 数据解析详解
ios
人生何处不修行20 小时前
iOS 自定义视频播放器实战:全屏旋转 + 画中画(PiP)+ 多页面切换不中断播放
macos·objective-c·cocoa