Recently, the company used cameras in its projects. Since the system's camera is not used, the camera cuts provided by the UI must be customized. I took the time to briefly study the customization of the camera.
The camera belongs to the system hardware, which requires us to manually call the iPhone's camera hardware, which is divided into the following steps:
1. First declare the following objects
#import <AVFoundation/> //Capturing devices, usually front camera, rear camera, microphone (audio input)@property (nonatomic, strong) AVCaptureDevice *device; //AVCaptureDeviceInput represents the input device, which uses AVCaptureDevice to initialize@property (nonatomic, strong) AVCaptureDeviceInput *input; //Output picture@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput; //session: It combines the input and output together and starts the capture device (camera)@property (nonatomic, strong) AVCaptureSession *session; //Image preview layer, display the captured images in real time@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;
2. Initialize each object
- (void)cameraDistrict { // AVCaptureDevicePositionBack rear camera// AVCaptureDevicePositionFront Front camera = [self cameraWithPosition:AVCaptureDevicePositionFront]; = [[AVCaptureDeviceInput alloc] initWithDevice: error:nil]; = [[AVCaptureStillImageOutput alloc] init]; = [[AVCaptureSession alloc] init]; // The size of the image you get can be set by yourself // AVCaptureSessionPreset320x240 // AVCaptureSessionPreset352x288 // AVCaptureSessionPreset640x480 // AVCaptureSessionPreset960x540 // AVCaptureSessionPreset1280x720 // AVCaptureSessionPreset1920x1080 // AVCaptureSessionPreset3840x2160 = AVCaptureSessionPreset640x480; //Combined input and output equipment if ([ canAddInput:]) { [ addInput:]; } if ([ canAddOutput:]) { [ addOutput:]; } //Generation of preview layer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:]; = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64); = AVLayerVideoGravityResizeAspectFill; [ addSublayer:]; //The device framing begins [ startRunning]; if ([_device lockForConfiguration:nil]) { //Automatic flash, if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) { [_device setFlashMode:AVCaptureFlashModeAuto]; } //Automatic white balance, but it seems that I can't get in. if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) { [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance]; } [_device unlockForConfiguration]; } }
Get the corresponding camera according to the front and rear positions:
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{ NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for ( AVCaptureDevice *device in devices ) if ( == position ){ return device; } return nil; }
3. Take a photo and get the corresponding picture:
- (void)photoBtnDidClick { AVCaptureConnection *conntion = [ connectionWithMediaType:AVMediaTypeVideo]; if (!conntion) { NSLog(@"Photo taken failed!"); return; } [ captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { if (imageDataSampleBuffer == nil) { return ; } NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; = [UIImage imageWithData:imageData]; [ stopRunning]; [ addSubview:]; }
4. Save photos to album:
#pragma - Save to album- (void)saveImageToPhotoAlbum:(UIImage*)savedImage { UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL); } // Specify callback method - (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo { NSString *msg = nil ; if(error != NULL){ msg = @"Save the image failed" ; }else{ msg = @"Save the picture successfully" ; } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Save the image result prompt" message:msg delegate:self cancelButtonTitle:@"Sure" otherButtonTitles:nil]; [alert show]; }
5. Switching front and rear cameras
- (void)changeCamera{ NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count]; if (cameraCount > 1) { NSError *error; //Add a flip animation to the camera switch CATransition *animation = [CATransition animation]; = .5f; = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; = @"oglFlip"; AVCaptureDevice *newCamera = nil; AVCaptureDeviceInput *newInput = nil; //Get another camera position AVCaptureDevicePosition position = [[_input device] position]; if (position == AVCaptureDevicePositionFront){ newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack]; = kCATransitionFromLeft;//Anime flip direction } else { newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront]; = kCATransitionFromRight;//Anime flip direction } //Generate new input newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil]; [ addAnimation:animation forKey:nil]; if (newInput != nil) { [ beginConfiguration]; [ removeInput:]; if ([ canAddInput:newInput]) { [ addInput:newInput]; = newInput; } else { [ addInput:]; } [ commitConfiguration]; } else if (error) { NSLog(@"toggle carema failed, error = %@", error); } } }
6. Other parameters of the camera
//AVCaptureFlashMode//AVCaptureFocusMode//AVCaptureExposureMode//AVCaptureWhiteBalanceMode//Flash and white balance can be set when generating the camera//Exposure should be determined based on the light condition of the focus point, so write it together with the focus point//point is the location of the click- (void)focusAtPoint:(CGPoint)point{ CGSize size = ; CGPoint focusPoint = CGPointMake( / ,/ ); NSError *error; if ([ lockForConfiguration:&error]) { //Focus mode and focus point if ([ isFocusModeSupported:AVCaptureFocusModeAutoFocus]) { [ setFocusPointOfInterest:focusPoint]; [ setFocusMode:AVCaptureFocusModeAutoFocus]; } //Exposure mode and exposure point if ([ isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) { [ setExposurePointOfInterest:focusPoint]; [ setExposureMode:AVCaptureExposureModeAutoExpose]; } [ unlockForConfiguration]; //Set focus animation _focusView.center = point; _focusView.hidden = NO; [UIView animateWithDuration:0.3 animations:^{ _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25); }completion:^(BOOL finished) { [UIView animateWithDuration:0.5 animations:^{ _focusView.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { _focusView.hidden = YES; }]; }]; } }
7. Some pitfalls and solutions encountered
1) Switching front and rear cameras
The values before and after cannot be switched, and I tried it for a long time but couldn't find it. Later I found out that when I set the image size to 1080P [canSetSessionPreset: AVCaptureSessionPreset1920x1080], the front camera does not support such a large size, so I cannot switch the front camera. I verified that the front camera supports up to 720P, and can be switched freely within 720P.
Of course, when switching between front and rear cameras, different sizes can be set according to the front and rear cameras, so I will not go into details here.
2) Focus position
CGPoint focusPoint = CGPointMake( / ,/ );
setExposurePointOfInterest: The Point value range after the focusPoint function is between the upper left corner of the frame (0, 0) and the lower right corner of the frame (1, 1). This is what the official wrote:
The value of this property is a CGPoint that determines the receiver's focus point of interest, if it has one. A value of (0,0) indicates that the camera should focus on the top left corner of the image, while a value of (1,1) indicates that it should focus on the bottom right. The default value is (0.5,0.5).
I also tried to click this but the position is wrong. I can only follow the above writing method. The front is the height of the y/PreviewLayer of the click position, and the back is the width of the x/PreviewLayer of the click position
3) Focus and exposure
When I set the focus, I first set the mode setFocusMode and then set the focus position, which will lead to a very strange phenomenon. The focus position is the position you clicked last time. So you must first set the position and then set the focus mode.
Exposure to the same as above
8. Write at the end
Attached demo:photographDemo
There are basically so many commonly used ones, and the writing is not perfect. If there is anything wrong, everyone is welcome to criticize and correct it and learn together.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.