iOS相機

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 100, 100);
    btn.center = self.view.center;
    [btn setTitle:@"拍照" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor orangeColor];
    [btn addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
   
    //會話
    _sesion = [[AVCaptureSession alloc] init];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        
        [_sesion setSessionPreset:AVCaptureSessionPresetPhoto];
    }
    
    AVCaptureDevice *device = [self cameraWithPosition: AVCaptureDevicePositionBack];
    
    
    //輸入源
    _input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
    if ([_sesion canAddInput:_input]) {
        
        [_sesion addInput:_input];
    }
    
    //輸出源
    _photoOut = [AVCaptureStillImageOutput new];
    if ([_sesion canAddOutput:_photoOut]) {
        
        [_sesion addOutput:_photoOut];
    }
    
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_sesion];
    _previewLayer.bounds = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    [self.view.layer addSublayer:_previewLayer];
    [_sesion startRunning];
}

- (void)clickAction {
    
    

    AVCaptureConnection *connect = [_photoOut connectionWithMediaType:AVMediaTypeVideo];
    [self.photoOut captureStillImageAsynchronouslyFromConnection:connect completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
        
     NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
     UIImage *image = [UIImage imageWithData:data];
     UIImageView *img = [[UIImageView alloc] initWithImage:image];
        img.frame = CGRectMake(20, 20, 100, 100);
        [self.view addSubview:img];
    }];
    
   
}



- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices ){
        if ( device.position == position )
            return device;
    }
          return nil;
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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