iOS 自定義相機(jī)

WechatIMG2.jpeg

WechatIMG1.jpeg

自定義相機(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;
            }];
        }];
    }
    
}

Demo:https://github.com/Garrett-Gyz/CustomCamera

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末疯暑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子哑舒,更是在濱河造成了極大的恐慌,老刑警劉巖幻馁,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件洗鸵,死亡現(xiàn)場離奇詭異,居然都是意外死亡仗嗦,警方通過查閱死者的電腦和手機(jī)膘滨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來稀拐,“玉大人火邓,你說我怎么就攤上這事〉虑耍” “怎么了铲咨?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蜓洪。 經(jīng)常有香客問我纤勒,道長,這世上最難降的妖魔是什么隆檀? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任摇天,我火速辦了婚禮粹湃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘泉坐。我一直安慰自己为鳄,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布腕让。 她就那樣靜靜地躺著济赎,像睡著了一般。 火紅的嫁衣襯著肌膚如雪记某。 梳的紋絲不亂的頭發(fā)上司训,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天,我揣著相機(jī)與錄音液南,去河邊找鬼壳猜。 笑死,一個(gè)胖子當(dāng)著我的面吹牛滑凉,可吹牛的內(nèi)容都是我干的统扳。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼畅姊,長吁一口氣:“原來是場噩夢啊……” “哼咒钟!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起若未,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤朱嘴,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后粗合,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體萍嬉,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年隙疚,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了壤追。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,953評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡供屉,死狀恐怖行冰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情伶丐,我是刑警寧澤悼做,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站撵割,受9級特大地震影響贿堰,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜啡彬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一羹与、第九天 我趴在偏房一處隱蔽的房頂上張望故硅。 院中可真熱鬧,春花似錦纵搁、人聲如沸吃衅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽徘层。三九已至,卻和暖如春利职,著一層夾襖步出監(jiān)牢的瞬間趣效,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工猪贪, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留跷敬,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓热押,卻偏偏與公主長得像西傀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子桶癣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容