iOS自定義相機(jī)界面

背景

由于項(xiàng)目中需要拍照功能脐帝,但是系統(tǒng)原生的相機(jī)功能根本滿足不了項(xiàng)目的需要拨黔,所以就只能自定義一個(gè)相加了逸雹。蘋果再AVFoundation框架中給我們提供了各個(gè)api止潘,我們完全可以通過這些api自定義一個(gè)滿足我們需求的相機(jī)搁拙。

關(guān)鍵類

AVCaptureSession 負(fù)責(zé)輸入流和輸出流的管理秒梳。
AVCaptureDeviceInput 輸入流。連接輸入采集設(shè)備的
AVCaptureStillImageOutput 輸出流箕速。AVCaptureOutput的子類酪碘,主要是負(fù)責(zé)采集圖片數(shù)據(jù)的,不過這個(gè)類再10.0以后廢棄掉了弧满,改用AVCapturePhotoOutput這個(gè)替換婆跑,這個(gè)類能夠支持RAW格式的圖片
AVCaptureVideoPreviewLayer 集成CALayer,負(fù)責(zé)將采集的視頻展示出來的一個(gè)類庭呜,提供了一個(gè)預(yù)覽功能而已

實(shí)現(xiàn)過程

#import "TakePictureViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIImage+Rotate.h"
#import "UIControl+Custom.h"

#define KSCREEN_WIDTH            [[UIScreen mainScreen] bounds].size.width
#define KSCREEN_HEIGHT           [[UIScreen mainScreen] bounds].size.height

typedef NS_ENUM(NSInteger, AVCamSetupResult ) {
    AVCamSetupResultSuccess,
    AVCamSetupResultCameraNotAuthorized,
    AVCamSetupResultSessionConfigurationFailed
};
@interface TakePictureViewController ()
{
    BOOL lightOn;
    AVCaptureDevice *device;
    ActivityIndicatorTipView *activityView;
}
// AVCaptureSession對象來執(zhí)行輸入設(shè)備和輸出設(shè)備之間的數(shù)據(jù)傳遞

@property (nonatomic, strong)AVCaptureSession *session;
// AVCaptureDeviceInput對象是輸入流

@property (nonatomic, strong)AVCaptureDeviceInput *videoInput;

// 照片輸出流對象

@property (nonatomic, strong)AVCaptureStillImageOutput *stillImageOutput;

// 預(yù)覽圖層滑进,來顯示照相機(jī)拍攝到的畫面

@property (nonatomic, strong)AVCaptureVideoPreviewLayer *previewLayer;
// 切換前后鏡頭的按鈕

@property (nonatomic, strong)UIButton *toggleButton;

// 放置預(yù)覽圖層的View
@property (nonatomic, strong)UIView *cameraShowView;



// 用來展示拍照獲取的照片

@property (nonatomic, strong)UIImageView *imageShowView;

@property (nonatomic,strong) UIView *overlayView;

@property (nonatomic) dispatch_queue_t sessionQueue;

@property (nonatomic) AVCamSetupResult setupResult;

@end

@implementation TakePictureViewController

-(BOOL)prefersStatusBarHidden
{
    return YES;
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        [self initAll];
    }
    return self;
}
- (void)initAll{
    [self initialSession];
    [self initCameraShowView];
    [self.view addSubview:self.overlayView];
    [self initAVDevice];
    [self setUpCameraLayer];
}
- (void)initialSession
{
    self.session = [[AVCaptureSession alloc] init];
}

- (void)initCameraShowView
{
    
    self.cameraShowView = [[UIView alloc] initWithFrame:self.view.frame];
    
    [self.view addSubview:self.cameraShowView];
}

// 這是獲取前后攝像頭對象的方法

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

- (AVCaptureDevice *)frontCamera
{
    return [self cameraWithPosition:AVCaptureDevicePositionFront];
}

- (AVCaptureDevice *)backCamera
{
    return [self cameraWithPosition:AVCaptureDevicePositionBack];
}
/**
 設(shè)備手電筒
 */
-(void)initAVDevice
{
    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if (![device hasTorch])
    {
        //無手電筒
        [[[UIAlertView alloc] initWithTitle:@"tishi" message:@"無手電筒" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil] show];
    }
    lightOn = NO;
}
- (void)configureSession{
   
    if ( self.setupResult != AVCamSetupResultSuccess ) {
        return;
    }
    
    [self.session beginConfiguration];//保證對AVCaptureSession設(shè)置的原子性與commitConfiguration配對使用

    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:nil];
    
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
     // 輸出流的設(shè)置參數(shù)AVVideoCodecJPEG參數(shù)表示以JPEG的圖片格式輸出圖片
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,@(0.1),AVVideoQualityKey,nil];
    
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    if ([self.session canAddInput:self.videoInput])
    {
        [self.session addInput:self.videoInput];
    }
    
    if ([self.session canAddOutput:self.stillImageOutput])
    {
        [self.session addOutput:self.stillImageOutput];
    }
    [self.session commitConfiguration];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
    switch ( [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] )
    {
        case AVAuthorizationStatusAuthorized:
        {
            break;
        }
        case AVAuthorizationStatusNotDetermined:
        {
            dispatch_suspend( self.sessionQueue );
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^( BOOL granted ) {
                if ( ! granted ) {
                    self.setupResult = AVCamSetupResultCameraNotAuthorized;
                }
                dispatch_resume( self.sessionQueue );
            }];
            break;
        }
        default:
        {
            self.setupResult = AVCamSetupResultCameraNotAuthorized;
            break;
        }
    }
    dispatch_async(self.sessionQueue, ^{
        [self configureSession];
    });
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    dispatch_async( self.sessionQueue, ^{
        switch ( self.setupResult )
        {
            case AVCamSetupResultSuccess:
            {
                [self.session startRunning];
                break;
            }
            case AVCamSetupResultCameraNotAuthorized:
            {
                dispatch_async( dispatch_get_main_queue(), ^{
                    NSString *message = @"請?jiān)试S拍照權(quán)限,以用來掃描二維碼";
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:cancelAction];
                    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"設(shè)置" style:UIAlertActionStyleDefault handler:^( UIAlertAction *action ) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                    }];
                    [alertController addAction:settingsAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                } );
                break;
            }
            case AVCamSetupResultSessionConfigurationFailed:
            {
                dispatch_async( dispatch_get_main_queue(), ^{
                    NSString *message = @"沒有拍照權(quán)限募谎,所以不能掃描二維碼";
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:cancelAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                } );
                break;
            }
        }
    } );
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    dispatch_async( self.sessionQueue, ^{
        if ( self.setupResult == AVCamSetupResultSuccess ) {
            [self.session stopRunning];
        }
    } );
}

- (void)setUpCameraLayer
{
    if (self.previewLayer == nil)
    {
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        
        UIView * view = self.cameraShowView;
        
        CALayer * viewLayer = [view layer];
        
        // UIView的clipsToBounds屬性和CALayer的setMasksToBounds屬性表達(dá)的意思是一致的,決定子視圖的顯示范圍扶关。當(dāng)取值為YES的時(shí)候,剪裁超出父視圖范圍的子視圖部分数冬,當(dāng)取值為NO時(shí)节槐,不剪裁子視圖搀庶。
        
        [viewLayer setMasksToBounds:YES];
        
        CGRect bounds = [view bounds];
        
        [self.previewLayer setFrame:bounds];
        
        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
        
        [viewLayer addSublayer:self.previewLayer];
    }
}

/**
 打開設(shè)備手電筒
 */
-(void) actionTurnOn
{
    [device lockForConfiguration:nil];
    
    [device setTorchMode:AVCaptureTorchModeOn];
    
    [device unlockForConfiguration];
}
/**
 關(guān)閉設(shè)備手電筒
 */
-(void) actionTurnOff
{
    [device lockForConfiguration:nil];
    
    [device setTorchMode: AVCaptureTorchModeOff];
    
    [device unlockForConfiguration];
}



// 拍照

- (void)actionStartCamera
{
    dispatch_async(self.sessionQueue, ^{
        AVCaptureConnection *videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
        
        if (!videoConnection)
        {
            return;
        }
        
        [self.stillImageOutput  captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
            
            if (imageDataSampleBuffer == NULL) {
                
                return;
                
            }
            
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            
            UIImage *originalImage = [UIImage imageWithData:imageData];
            //1.旋轉(zhuǎn)照片
            UIImage *rotateImage = [originalImage rotate:UIImageOrientationRight];
    });
}
@end

注意點(diǎn)

1、AVCaptureSession的配置過程和startRunning是阻擋主線程的一個(gè)耗時(shí)操作铜异,所以我們放到另外的queue中操作哥倔,能夠避免阻擋主線程
2、由于我們拍照不需要質(zhì)量非常高的照片揍庄,所以我們通過setOutputSettings設(shè)置了圖片質(zhì)量咆蒿,這樣減少了很大一部分內(nèi)存,可以根據(jù)情況來設(shè)置圖片的質(zhì)量蚂子。
3沃测、拍完照片圖片是倒立的,所以我們做了一個(gè)旋轉(zhuǎn)操作食茎,將圖片正立了過來

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蒂破,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子别渔,更是在濱河造成了極大的恐慌附迷,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件钠糊,死亡現(xiàn)場離奇詭異挟秤,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)抄伍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來管宵,“玉大人截珍,你說我怎么就攤上這事÷崞樱” “怎么了岗喉?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長炸庞。 經(jīng)常有香客問我钱床,道長,這世上最難降的妖魔是什么埠居? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任查牌,我火速辦了婚禮,結(jié)果婚禮上纸颜,老公的妹妹穿的比我還像新娘。我一直安慰自己绎橘,他們只是感情好胁孙,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般涮较。 火紅的嫁衣襯著肌膚如雪稠鼻。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天狂票,我揣著相機(jī)與錄音候齿,去河邊找鬼。 笑死苫亦,一個(gè)胖子當(dāng)著我的面吹牛毛肋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播屋剑,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼润匙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了唉匾?” 一聲冷哼從身側(cè)響起孕讳,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎巍膘,沒想到半個(gè)月后厂财,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡峡懈,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年璃饱,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肪康。...
    茶點(diǎn)故事閱讀 39,769評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡荚恶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出磷支,到底是詐尸還是另有隱情谒撼,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布雾狈,位于F島的核電站廓潜,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏善榛。R本人自食惡果不足惜辩蛋,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望锭弊。 院中可真熱鬧堪澎,春花似錦、人聲如沸味滞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至昨凡,卻和暖如春爽醋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背便脊。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工蚂四, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人哪痰。 一個(gè)月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓遂赠,卻偏偏與公主長得像,于是被迫代替她去往敵國和親晌杰。 傳聞我的和親對象是個(gè)殘疾皇子跷睦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評論 2 354

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