ios 拍照功能簡單實(shí)現(xiàn)

storyboard.png

import <MobileCoreServices/MobileCoreServices.h>

import "ViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
UIImagePickerController * _imagePickerController;
}
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    btn.backgroundColor = [UIColor purpleColor];
    [btn addTarget:self action:@selector(gotoPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    // Do any additional setup after loading the view, typically from a nib.
    }

  • (void)gotoPhoto
    {
    NSLog(@"photo");
    self.imageView.backgroundColor = [UIColor yellowColor];
    [self setupImagePickerController];
    }

/*創(chuàng)建對(duì)象/

  • (void)setupImagePickerController
    {
    //第一步:判斷攝像頭是否打開
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
    //第二步:實(shí)例化UIImagePickerController對(duì)象
    _imagePickerController = [[UIImagePickerController alloc] init];
    //第三步:告訴picker對(duì)象是獲取相機(jī)資源
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    //第四步:設(shè)置代理
    _imagePickerController.delegate = self;
    //第五步:設(shè)置picker可以編輯
    _imagePickerController.allowsEditing = YES;
    //第六步:設(shè)置進(jìn)去的模態(tài)方式
    _imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    //第七步:跳轉(zhuǎn)
    [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
    }

pragma mark --代理方法UIImagePickerControllerDelegate--

  • (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
    {
    //獲取選中資源的類型
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //只能拍照(還有攝像或者二者都可以有的)
    NSString *requiredMediaType = (NSString *)kUTTypeImage;
    if([mediaType isEqualToString:requiredMediaType])
    {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    self.imageView.image = image;
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    }

pragma mark --取消選擇圖片

  • (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
    {
    [picker dismissViewControllerAnimated:YES completion:nil];
    }

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }
    @end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容