自定義相機(jī)娄昆,實(shí)現(xiàn)上面兩張圖片的功能佩微。
首先實(shí)現(xiàn)相機(jī)的基本功能:數(shù)據(jù)流的輸入和輸出
定義屬性:
//捕獲設(shè)備,通常是前置攝像頭萌焰,后置攝像頭哺眯,麥克風(fēng)(音頻輸入)
@property(nonatomic)AVCaptureDevice *device;
//AVCaptureDeviceInput 代表輸入設(shè)備,他使用AVCaptureDevice 來初始化
@property(nonatomic)AVCaptureDeviceInput *input;
//當(dāng)啟動(dòng)攝像頭開始捕獲輸入
@property(nonatomic)AVCaptureMetadataOutput *output;
@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;
//session:由他把輸入輸出結(jié)合在一起扒俯,并開始啟動(dòng)捕獲設(shè)備(攝像頭)
@property(nonatomic)AVCaptureSession *session;
//圖像預(yù)覽層奶卓,實(shí)時(shí)顯示捕獲的圖像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;
數(shù)據(jù)的獲取和展示:
- (void)customCamera{
self.view.backgroundColor = [UIColor whiteColor];
//使用AVMediaTypeVideo 指明self.device代表視頻,默認(rèn)使用后置攝像頭進(jìn)行初始化
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//使用設(shè)備初始化輸入
self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
//生成輸出對象
self.output = [[AVCaptureMetadataOutput alloc]init];
self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
//生成會話撼玄,用來結(jié)合輸入輸出
self.session = [[AVCaptureSession alloc]init];
if ([self.session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
self.session.sessionPreset = AVCaptureSessionPresetHigh;
}
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
if ([self.session canAddOutput:self.ImageOutPut]) {
[self.session addOutput:self.ImageOutPut];
}
//使用self.session夺姑,初始化預(yù)覽層,self.session負(fù)責(zé)驅(qū)動(dòng)input進(jìn)行信息的采集互纯,layer負(fù)責(zé)把圖像渲染顯示
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
//228x362
// self.previewLayer.frame = CGRectMake((kScreenWidth - 228.0 / 375.0) / 2, (kScreenHeight - 362.0 / 667.0) / 2, 228.0 / 375.0, 362.0 / 667.0);
self.previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:self.previewLayer];
//開始啟動(dòng)
[self.session startRunning];
if ([_device lockForConfiguration:nil]) {
if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
[_device setFlashMode:AVCaptureFlashModeAuto];
}
//自動(dòng)白平衡
if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
[_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
[_device unlockForConfiguration];
}
}
此時(shí)已經(jīng)生成了一個(gè)全屏的相機(jī)瑟幕。要實(shí)現(xiàn)圖1的效果,需要在預(yù)覽層self.previewLayer上面添加一個(gè)圖片(四周0.7透明度留潦,中間全透明)以及拍攝和取消兩個(gè)按鈕只盹。
_bgImage = [[UIImageView alloc] init];
[self.view addSubview:_bgImage];
[_bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(self.view);
}];
_bgImage.image = [UIImage imageNamed:@"Mine_camera_bg"];
_bgImage.alpha = 0.7;
_bgImage.userInteractionEnabled = YES;
_PhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_PhotoButton setImage:[UIImage imageNamed:@"Mine_camera_button"] forState: UIControlStateNormal];
// [_PhotoButton setImage:[UIImage imageNamed:@"Mine_camera_button"] forState:UIControlStateNormal];
[_PhotoButton addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside];
[_bgImage addSubview:_PhotoButton];
[_PhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.mas_equalTo(_bgImage.mas_centerX);
make.bottom.mas_offset(-41);
make.size.mas_equalTo(CGSizeMake(70, 70));
}];
UIButton *quitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[quitBtn setTitle:@"取消" forState:UIControlStateNormal];
[quitBtn setTitleColor:Colorffffff forState:UIControlStateNormal];
[quitBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
[_bgImage addSubview:quitBtn];
[quitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.mas_equalTo(_PhotoButton.mas_centerY);
make.right.mas_equalTo(_PhotoButton.mas_left).offset(-60);
make.size.mas_equalTo(CGSizeMake(60, 50));
}];
WEAKSELF
[quitBtn addTapBlock:^(id obj) {
STRONGSELF
[strongSelf dismissViewControllerAnimated:YES completion:^{
}];
}];
點(diǎn)擊拍攝,生成圖片兔院。
- (void) shutterCamera
{
AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
if (!videoConnection) {
NSLog(@"take photo failed!");
return;
}
videoConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeStandard;
[self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer == NULL) {
return;
}
NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
self.image = [UIImage imageWithData:imageData];
[self.session stopRunning];
//顯示預(yù)覽層
[self showImageAction];
}];
}
此時(shí)生成了一張全屏的圖片殖卑,如果要實(shí)現(xiàn)圖2的預(yù)覽圖片界面。需要把圖片進(jìn)行幾步處理坊萝。
1.之前設(shè)置圖像輸出的時(shí)候孵稽,設(shè)置了AVCaptureSessionPresetHigh這個(gè)參數(shù)许起,意思是生成的圖片質(zhì)量是當(dāng)前設(shè)備支持的最高設(shè)備,所以此時(shí)生成的圖片的尺寸并不是屏幕的尺寸菩鲜,例如我使用的8p,生成的圖片的尺寸為1080*1992园细。 所以第一步需要將圖片的尺寸轉(zhuǎn)換成屏幕尺寸。
2.然后在圖片中截取和圖1上面中間透明的一塊圖片接校。
3.將圖片旋轉(zhuǎn)90度猛频,生成圖2中橫向的圖片。
//將原來的圖片尺寸更改為屏幕尺寸
self.image = [self image:self.image scaleToSize:CGSizeMake(kScreenWidth, kScreenHeight)];
//生成一個(gè)固定尺寸的圖片
CGSize oldImageSize = CGSizeMake(self.image.size.width * 3, self.image.size.height * 3);
CGFloat newImageWidth = 228.0 / 375.0 * oldImageSize.width;
CGFloat newImageHeight = 362.0 / 667.0 * oldImageSize.height;
UIImage *scaleImage = [self imageFromImage:self.image inRect:CGRectMake((oldImageSize.width - newImageWidth) / 2, (oldImageSize.height - newImageHeight) / 2, newImageWidth, newImageHeight)];
//旋轉(zhuǎn)圖片
self.showImage = [scaleImage imageByRotateLeft90];
此時(shí)生成的self.showImage就是我們最終想要的圖片蛛勉。
上面代碼用到的方法
//截取圖片
-(UIImage*)image:(UIImage *)imageI scaleToSize:(CGSize)size{
/*
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
CGSize size:指定將來創(chuàng)建出來的bitmap的大小
BOOL opaque:設(shè)置透明YES代表透明鹿寻,NO代表不透明
CGFloat scale:代表縮放,0代表不縮放
創(chuàng)建出來的bitmap就對應(yīng)一個(gè)UIImage對象
*/
UIGraphicsBeginImageContextWithOptions(size, NO, 3.0); //此處將畫布放大三倍,這樣在retina屏截取時(shí)不會影響像素
[imageI drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
需要注意的是诽凌,在這里將畫布放大了三倍毡熏,獲得的圖片尺寸雖然是屏幕的正常尺寸,但是在計(jì)算尺寸的時(shí)候要將寬和高都*3來計(jì)算侣诵。
-(UIImage *)imageFromImage:(UIImage *)imageI inRect:(CGRect)rect{
CGImageRef sourceImageRef = [imageI CGImage];
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
return newImage;
}
最后添加圖2的UI就大功告成了痢法。
最后,還有一些相機(jī)的功能窝趣。
切換攝像頭
- (void)changeCamera{
NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
if (cameraCount > 1) {
NSError *error;
CATransition *animation = [CATransition animation];
animation.duration = .5f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = @"oglFlip";
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
AVCaptureDevicePosition position = [[_input device] position];
if (position == AVCaptureDevicePositionFront){
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
animation.subtype = kCATransitionFromLeft;
}
else {
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
animation.subtype = kCATransitionFromRight;
}
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
[self.previewLayer addAnimation:animation forKey:nil];
if (newInput != nil) {
[self.session beginConfiguration];
[self.session removeInput:_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);
}
}
}
控制閃關(guān)燈開關(guān)
//- (void)FlashOn{
// if ([_device lockForConfiguration:nil]) {
// if (_isflashOn) {
// if ([_device isFlashModeSupported:AVCaptureFlashModeOff]) {
// [_device setFlashMode:AVCaptureFlashModeOff];
// _isflashOn = NO;
// [_flashButton setTitle:@"閃光燈關(guān)" forState:UIControlStateNormal];
// }
// }else{
// if ([_device isFlashModeSupported:AVCaptureFlashModeOn]) {
// [_device setFlashMode:AVCaptureFlashModeOn];
// _isflashOn = YES;
// [_flashButton setTitle:@"閃光燈開" forState:UIControlStateNormal];
// }
// }
//
// [_device unlockForConfiguration];
// }
//}
聚焦
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position ) return device;
return nil;
}
- (void)focusGesture:(UITapGestureRecognizer*)gesture{
CGPoint point = [gesture locationInView:gesture.view];
[self focusAtPoint:point];
}
- (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]) {
if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[self.device setFocusPointOfInterest:focusPoint];
[self.device setFocusMode:AVCaptureFocusModeAutoFocus];
}
if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
[self.device setExposurePointOfInterest:focusPoint];
[self.device setExposureMode:AVCaptureExposureModeAutoExpose];
}
[self.device unlockForConfiguration];
_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;
}];
}];
}
}