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
相关推荐
ch_ziyuan4 分钟前
2026新优化神马TV8.5影视点播系统保姆级搭建教程:三后台配置+反编译修改
android·ios·php
2601_9557674224 分钟前
观复盾 iPhone 17 Pro 护景贴深度评测:参数解析与实测避坑
人工智能·ios·ar·iphone·圆偏振光·磁控溅射
一拳一个娘娘腔2 小时前
【SRC漏洞挖掘系列】第11期:移动端安全(Android/iOS)—— APP 里的“猫腻”大起底
android·安全·ios
搬砖的小码农_Sky2 小时前
macOS Sequoia上如何安装Python开发环境?
开发语言·python·macos
码农阿强3 小时前
OpenAI Codex 全平台详细安装与配置教程(Windows/Mac/Linux)
linux·windows·macos·ai
lxllzwj52013143 小时前
Mac如何像shell一样丝滑的使用item2连接服务器.
服务器·macos·github
学习3人组3 小时前
IOS手机使用电脑代理 IP 作为网关/代理出口实现穿越上网
tcp/ip·ios·智能手机
2501_915106323 小时前
深入解析HTTPS抓包原理、中间人攻击及反抓包技术攻防
数据库·网络协议·ios·小程序·https·uni-app·iphone
搬砖的小码农_Sky4 小时前
macOS Sequoia上如何安装gcc/g++环境?
c语言·c++·macos
ch_ziyuan4 小时前
跨平台APP封装分发系统搭建:iOS免签+安卓防报毒+IPA签名一体化
android·ios