溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在iOS中自定義相機實現(xiàn)拍照、錄制視頻

發(fā)布時間:2021-05-31 17:49:16 來源:億速云 閱讀:330 作者:Leah 欄目:移動開發(fā)

怎么在iOS中自定義相機實現(xiàn)拍照、錄制視頻?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

首先聲明以下對象:

#import "CustomeCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
 
@interface CustomeCameraViewController ()<AVCaptureFileOutputRecordingDelegate>
 
{
  // AVCaptureSession對象來執(zhí)行輸入設備和輸出設備之間的數(shù)據(jù)傳遞
  AVCaptureSession *iSession;
  //當前設備
  AVCaptureDevice *iDevice;
  //輸入設備
  AVCaptureDeviceInput *iDeviceInput;
  //照片輸出流
  AVCaptureStillImageOutput *iStillImageOutput;
  //預覽圖層
  AVCaptureVideoPreviewLayer *iPreviewLayer;
  
}

初始化各對象:

- (void)viewDidLoad {
  [super viewDidLoad];
  
  //點擊屏幕對焦
  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusTap:)];
  [self.view addGestureRecognizer:tap];
  
  
  iSession = [[AVCaptureSession alloc]init];
  
  NSArray *deviceArray = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  for (AVCaptureDevice *device in deviceArray) {
    
    //AVCaptureDevicePositionBack 后置攝像頭
    //AVCaptureDevicePositionFront 前置攝像頭
    if (device.position == AVCaptureDevicePositionBack) {
      iDevice = device;
    }
  }
  
  
  iSession.sessionPreset = [self getSessionPresetForDevice:iDevice];
  
  iDeviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:iDevice error:nil];
  
  
  ////輸出設置。AVVideoCodecJPEG  輸出jpeg格式圖片
  iStillImageOutput = [[AVCaptureStillImageOutput alloc]init];
  NSDictionary *outputDic = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
  [iStillImageOutput setOutputSettings:outputDic];
  
  
  //更改這個設備設置的時候必須先鎖定設備,修改完后再解鎖,否則崩潰
  [iDevice lockForConfiguration:nil];
  if ([iDevice isFlashModeSupported:AVCaptureFlashModeOff]) {
    [iDevice setFlashMode:AVCaptureFlashModeOff];
  }
  if ([iDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
    [iDevice setFocusMode:AVCaptureFocusModeAutoFocus];
  }
  if ([iDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
    [iDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
  }
  [iDevice unlockForConfiguration];
  
  if ([iSession canAddInput:iDeviceInput]) {
    [iSession addInput:iDeviceInput];
  }
  if ([iSession canAddOutput:iStillImageOutput]) {
    [iSession addOutput:iStillImageOutput];
  }
  if ([iSession canAddOutput:iVideoOutput]) {
    [iSession addOutput:iVideoOutput];
  }
  
  //初始化預覽圖層
  iPreviewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:iSession];
  [iPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
  iPreviewLayer.frame = CGRectMake(0, 60, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-160);
  [self.iCameraView.layer addSublayer:iPreviewLayer];
  
  [iSession startRunning];
  
  
}

點擊按鈕拍照:

//拍照
-(void)takePictures{
  AVCaptureConnection *connection = [iStillImageOutput connectionWithMediaType:AVMediaTypeVideo];
  if (!connection) {
    NSLog(@"失敗");
    return;
  }
  //設置焦距
  [connection setVideoScaleAndCropFactor:1];
  
  [iStillImageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
    if (imageDataSampleBuffer==NULL) {
      NSLog(@"NUll");
      return ;
    }
    
    NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
    UIImage *image = [UIImage imageWithData:data];
    
    
  }];
}

image即為拍照所得圖片:

設置session的AVCaptureSessionPreset屬性

-(NSString *)getSessionPresetForDevice:(AVCaptureDevice *)device{
  if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset3840x2160]) {
    return AVCaptureSessionPreset3840x2160;
  } else if([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1920x1080]){
    return AVCaptureSessionPreset1920x1080;
  } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1280x720]){
    return AVCaptureSessionPreset1280x720;
  } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset640x480]){
    return AVCaptureSessionPreset640x480;
  } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset352x288]){
    return AVCaptureSessionPreset352x288;
  } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPresetHigh]){
    return AVCaptureSessionPresetHigh;
  } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPresetMedium]){
    return AVCaptureSessionPresetMedium;
  } else{
    return AVCaptureSessionPresetLow;
  }
}

設置閃光燈:

- (IBAction)iFlashBtn:(id)sender {
  
  [iDevice lockForConfiguration:nil];
  if (iDevice.flashMode == AVCaptureFlashModeOff) {
    if ([iDevice isFlashModeSupported:AVCaptureFlashModeOn]) {
      [iDevice setFlashMode:AVCaptureFlashModeOn];
      
      [self.iFlashBtn setBackgroundImage:[UIImage imageNamed:@"flashBtn"] forState:UIControlStateNormal];
    }
  } else if (iDevice.flashMode == AVCaptureFlashModeOn){
    if ([iDevice isFlashModeSupported:AVCaptureFlashModeOff]) {
      [iDevice setFlashMode:AVCaptureFlashModeOff];
      
       [self.iFlashBtn setBackgroundImage:[UIImage imageNamed:@"flashOffBtn"] forState:UIControlStateNormal];
    }
  }
  [iDevice unlockForConfiguration];
  
}

切換前置攝像頭與后置攝像頭:

- (IBAction)iChangeBtn:(id)sender {
  
  
  NSArray *array = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  AVCaptureDevice *newDevice = nil;
  AVCaptureDeviceInput *newDeviceInput = nil;
  
  CATransition *animation = [CATransition animation];
  animation.duration = 0.5f;
  animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  animation.type = @"oglFlip";
  
  if (iDevice.position == AVCaptureDevicePositionBack) {
    animation.subtype = kCATransitionFromLeft;
    for (AVCaptureDevice *device in array) {
      if (device.position == AVCaptureDevicePositionFront) {
        newDevice = device;
      }
    }
  } else if (iDevice.position == AVCaptureDevicePositionFront){
    animation.subtype = kCATransitionFromRight;
    for (AVCaptureDevice *device in array) {
      if (device.position == AVCaptureDevicePositionBack) {
        newDevice = device;
      }
    }
  }
  
  newDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:newDevice error:nil];
  [iPreviewLayer addAnimation:animation forKey:nil];
  if (newDeviceInput!=nil) {
    [iSession beginConfiguration];
    [iSession removeInput:iDeviceInput];
     iSession.sessionPreset = [self getSessionPresetForDevice:newDevice];
    if ([iSession canAddInput:newDeviceInput]) {
      [iSession addInput:newDeviceInput];
      iDeviceInput = newDeviceInput;
      iDevice = newDevice;
    } else {
      [iSession addInput:iDeviceInput];
    }
    [iSession commitConfiguration];
  }
  
  
}

點擊屏幕對焦:

//點擊屏幕對焦
-(void)focusTap:(UIGestureRecognizer *)tap{
  CGPoint tapPoint = [tap locationInView:self.view];
  
  
  float Y = tapPoint.y;
  if (Y<60 || Y>([UIScreen mainScreen].bounds.size.height-100)) {
    return;
  }
  
  [iDevice lockForConfiguration:nil];
  if ([iDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
    [iDevice setFocusPointOfInterest:CGPointMake(tapPoint.x/self.view.frame.origin.x, tapPoint.y/self.view.frame.origin.y)];
    [iDevice setFocusMode:AVCaptureFocusModeAutoFocus];
  }
  [iDevice unlockForConfiguration];
  
  self.iFocusImgView.center = tapPoint;
  self.iFocusImgView.hidden = NO;
  [UIView animateWithDuration:0.3 animations:^{
    self.iFocusImgView.transform = CGAffineTransformMakeScale(1.25, 1.25);
  }completion:^(BOOL finished) {
    [UIView animateWithDuration:0.5 animations:^{
      self.iFocusImgView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
      self.iFocusImgView.hidden = YES;
    }];
  }];
}

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

ios
AI