Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop a custom camera using iOS

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to use iOS to develop custom cameras. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Declare the following objects first

# import / / capture device, usually front camera, rear camera, microphone (audio input) @ property (nonatomic, strong) AVCaptureDevice * device;//AVCaptureDeviceInput represents input device, he uses AVCaptureDevice to initialize @ property (nonatomic, strong) AVCaptureDeviceInput * input;// output image @ property (nonatomic, strong) AVCaptureStillImageOutput * imageOutput;//session: he combines input and output and starts the capture device (camera) @ property (nonatomic, strong) AVCaptureSession * session / / Image preview layer, which displays the captured image @ property (nonatomic, strong) AVCaptureVideoPreviewLayer * previewLayer in real time.

2. Initialize each object

-(void) cameraDistrict {/ / AVCaptureDevicePositionBack rear camera / / AVCaptureDevicePositionFront front camera self.device = [self cameraWithPosition:AVCaptureDevicePositionFront]; self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil]; self.imageOutput = [[AVCaptureStillImageOutput alloc] init]; self.session = [[AVCaptureSession alloc] init]; / / you can set the size of the obtained image by yourself / / AVCaptureSessionPreset320x240 / / AVCaptureSessionPreset352x288 / / AVCaptureSessionPreset640x480 / / AVCaptureSessionPreset960x540 / / AVCaptureSessionPreset1280x720 / AVCaptureSessionPreset1920x1080 / / AVCaptureSessionPreset3840x2160 self.session.sessionPreset = AVCaptureSessionPreset640x480 / / input / output devices combine if ([self.session canAddInput:self.input]) {[self.session addInput:self.input];} if ([self.session canAddOutput:self.imageOutput]) {[self.session addOutput:self.imageOutput];} / / Preview layer generation self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session]; self.previewLayer.frame = CGRectMake (0,64, SCREEN_WIDTH, SCREEN_HEIGHT-64); self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill [self.view.layer addSublayer:self.previewLayer]; / / device view starts [self.session startRunning]; if ([_ device lockForConfiguration:nil]) {/ / automatic flash, if ([_ device isFlashModeSupported:AVCaptureFlashModeAuto]) {[_ device setFlashMode:AVCaptureFlashModeAuto];} / / automatic white balance, but it seems to be unable to enter if ([_ device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {[_ device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];} [_ device unlockForConfiguration];}} all the time.

Get the corresponding camera according to the front and rear position:

-(AVCaptureDevice *) cameraWithPosition: (AVCaptureDevicePosition) position {NSArray * devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice * device in devices) if (device.position = = position) {return device;} return nil;}

3. Take a picture and get the corresponding picture:

-(void) photoBtnDidClick {AVCaptureConnection * conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo]; if (! conntion) {NSLog (@ "Photo failed!"); return;} [self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler: ^ (CMSampleBufferRef imageDataSampleBuffer, NSError * error) {if (imageDataSampleBuffer = = nil) {return;} NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; self.image = [UIImage imageWithData:imageData]; [self.session stopRunning]; [self.view addSubview:self.cameraImageView];}

4. Save the photo to the 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 = @ "failed to save picture";} else {msg = @ "saved picture successfully" } UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@ "Save picture result prompt" message:msg delegate:self cancelButtonTitle:@ "to confirm" otherButtonTitles:nil]; [alert show];}

5. Switch between front and rear cameras

-(void) changeCamera {NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count]; if (cameraCount > 1) {NSError * error; / / add flip animation CATransition * animation = [CATransition animation] to camera switching; animation.duration = .5f Animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; animation.type = @ "oglFlip"; AVCaptureDevice * newCamera = nil; AVCaptureDeviceInput * newInput = nil; / / get another camera position AVCaptureDevicePosition position = [_ input device] position]; if (position = = AVCaptureDevicePositionFront) {newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack]; animation.subtype = kCATransitionFromLeft;// Animation Flip Direction} else {newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront]; animation.subtype = kCATransitionFromRight / / Animation flip direction} / / generate a new input newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil]; [self.previewLayer addAnimation:animation forKey:nil]; if (newInput! = nil) {[self.session beginConfiguration]; [self.session removeInput:self.input]; if ([self.session canAddInput:newInput]) {[self.session addInput:newInput]; self.input = newInput;} else {[self.session addInput:self.input];} [self.session commitConfiguration] } else if (error) {NSLog (@ "toggle carema failed, error =% @", error);}

6. Other parameters of the camera.

/ / AVCaptureFlashMode flash / / AVCaptureFocusMode focus / / AVCaptureExposureMode exposure / / AVCaptureWhiteBalanceMode white balance / / flash and white balance can be set when generating the camera / / exposure depends on the light condition of the focus, so write / / point with focus as the click position-(void) focusAtPoint: (CGPoint) point {CGSize size = self.view.bounds.size; CGPoint focusPoint = CGPointMake (point.y / size.height, 1-point.x/size.width); NSError * error If ([self.device lockForConfiguration:&error]) {/ / focus mode and focus if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {[self.device setFocusPointOfInterest:focusPoint]; [self.device setFocusMode:AVCaptureFocusModeAutoFocus];} / exposure mode and exposure point if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {[self.device setExposurePointOfInterest:focusPoint]; [self.device setExposureMode:AVCaptureExposureModeAutoExpose];} [self.device 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 pits encountered and solutions

1) switch between front and rear cameras

Before and after the value can not be switched, a variety of attempts for a long time did not find a reason. Later, I found that when I set the image size to 1080p [self.session canSetSessionPreset: AVCaptureSessionPreset1920x1080], the front camera does not support such a large size, so I can't switch the front camera. I verified that the front camera supports up to 720p and can be switched freely within 720p.

Of course, you can also set different sizes according to the front and rear cameras when switching between front and rear cameras. I will not repeat them here.

2) focus position

CGPoint focusPoint = CGPointMake (point.y / size.height, 1-point.x/size.width); the value of Point after the setExposurePointOfInterest:focusPoint function ranges from the upper left corner of the viewfinder (0mem0) to the lower right corner of the viewfinder (1mem1). Here's what the official line says:

The value of this property is a CGPoint that determines the receiver's focus point of interest, if it has one. A value of (0mem0) indicates that the camera should focus on the top left corner of the image, while a value of (1mem1) indicates that it should focus on the bottom right. The default value is (0.5, 0.5).

I also tried to press this, but the position is not right, can only be written according to the above. The height of the y/PreviewLayer in front of the click location, followed by 1-the width of the x/PreviewLayer in the click location

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 be sure to set the position first, and then set the focus mode. Exposure same as above

Thank you for reading! This is the end of this article on "how to use iOS to develop a custom camera". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report