iOS 自定義相機拍照,手動對焦和自動對焦

天下虛懷接空谷领虹,何處高峰不入云烹俗。

一、相機界面繪制需要的一些宏

#define kScreenBounds   [UIScreen mainScreen].bounds
#define kPhotographWidth  100   //拍攝區(qū)域寬度
#define kPhotographHeight  400   //拍攝區(qū)域高度
#define kBackgroudColor [UIColor colorWithWhite:0 alpha:.7] //遮罩顏色
#define kTopBackgroudColor [UIColor colorWithWhite:0 alpha:.9] //遮罩顏色

#define kShadeTopHeight StatusBarAndNavigationBarHeight//導航欄高度
#define kShadeBottomHeight 84//底部拍攝按鈕高度

#define kTopHeight ((SCREEN_HEIGHT-kPhotographHeight-kShadeTopHeight-kShadeBottomHeight)/2)
#define kLeftWidth ((SCREEN_WIDTH-kPhotographWidth)/2)

typedef void(^PropertyChangeBlock)(AVCaptureDevice *captureDevice);

二嘹锁、屬性的申明

@property (nonatomic,strong)AVCaptureDevice* device;
@property (nonatomic,strong)AVCaptureStillImageOutput *ImageOutPut;
@property (nonatomic,strong)AVCaptureSession *session;
@property (nonatomic,strong)AVCaptureDeviceInput* input;
@property (strong,nonatomic)  UIImageView *focusCursor; //聚焦光標

三、正文開始

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    if (self.session) {
        [self.session stopRunning];
    }
}

自定義相機代碼

- (void)customCamera{
    //對焦手勢,方法在下面
    [self addGenstureRecognizer];
    AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //在修改devicce之前一定要調用lock方法,否則會引起崩潰
    [device lockForConfiguration:nil];
    if ([device isFlashModeSupported:AVCaptureFlashModeAuto]) {
        [device setFlashMode:AVCaptureFlashModeAuto];
    }
    if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
        [device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
    }
//設置完成后調用unlock
    [device unlockForConfiguration];
    _device=device;
    //captureDeviceInput
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil];
    self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        self.session.sessionPreset = AVCaptureSessionPresetHigh;
    }
    //注意添加區(qū)域改變捕獲通知必須首先設置設備允許捕獲
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        captureDevice.subjectAreaChangeMonitoringEnabled=YES;
    }];
//自動對象,蘋果提供了對應的通知api接口,可以直接添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:self.device];
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    [self.session commitConfiguration];
    //開始啟動
    [self.session startRunning];
    dispatch_async(dispatch_get_main_queue(), ^{
        AVCaptureVideoPreviewLayer* previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
        previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        previewLayer.videoGravity = AVLayerVideoGravityResize;
        [self.view.layer insertSublayer:previewLayer atIndex:0];
    });
}

改變設備屬性的方法

//通過給屏幕上的view添加手勢,獲取手勢的坐標.將坐標用setFocusPointOfInterest方法賦值給device
-(void)changeDeviceProperty:(PropertyChangeBlock)propertyChange{
    AVCaptureDevice *captureDevice= [self.input device];
    NSError *error;
    //注意改變設備屬性前一定要首先調用lockForConfiguration:調用完之后使用unlockForConfiguration方法解鎖
    if ([captureDevice lockForConfiguration:&error]) {
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
    }else{
        NSLog(@"設置設備屬性過程發(fā)生錯誤着裹,錯誤信息:%@",error.localizedDescription);
    }
}

手動對焦的方法

-(void)addGenstureRecognizer{
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapScreen:)];
    [_middleView addGestureRecognizer:tapGesture];
}
- (void)tapScreen:(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];
        }
        [self.device unlockForConfiguration];
    }
    [self setFocusCursorWithPoint:point];
}

自動對焦的方法

- (void)subjectAreaDidChange:(NSNotification *)notification
{
    //先進行判斷是否支持控制對焦
    if (_device.isFocusPointOfInterestSupported &&[_device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
        NSError *error =nil;
        //對cameraDevice進行操作前领猾,需要先鎖定,防止其他線程訪問骇扇,
        [_device lockForConfiguration:&error];
        [_device setFocusMode:AVCaptureFocusModeAutoFocus];
        [self focusAtPoint:_middleView.center];
        //操作完成后摔竿,記得進行unlock。
        [_device unlockForConfiguration];
    }
}
-(void)setFocusCursorWithPoint:(CGPoint)point{
     //下面是手觸碰屏幕后對焦的效果
    _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;
        }];
    }];
    
}

代碼貼完,有待修改

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末少孝,一起剝皮案震驚了整個濱河市继低,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌韭山,老刑警劉巖郁季,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異钱磅,居然都是意外死亡,警方通過查閱死者的電腦和手機似枕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進店門盖淡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人凿歼,你說我怎么就攤上這事褪迟∪吆蓿” “怎么了?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵味赃,是天一觀的道長掀抹。 經(jīng)常有香客問我,道長心俗,這世上最難降的妖魔是什么傲武? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮城榛,結果婚禮上揪利,老公的妹妹穿的比我還像新娘。我一直安慰自己狠持,他們只是感情好疟位,可當我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著喘垂,像睡著了一般甜刻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上正勒,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天罢吃,我揣著相機與錄音,去河邊找鬼昭齐。 笑死尿招,一個胖子當著我的面吹牛,可吹牛的內容都是我干的阱驾。 我是一名探鬼主播就谜,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼里覆!你這毒婦竟也來了丧荐?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤喧枷,失蹤者是張志新(化名)和其女友劉穎虹统,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體隧甚,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡车荔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了戚扳。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片忧便。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖帽借,靈堂內的尸體忽然破棺而出珠增,到底是詐尸還是另有隱情超歌,我是刑警寧澤,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布蒂教,位于F島的核電站巍举,受9級特大地震影響,放射性物質發(fā)生泄漏凝垛。R本人自食惡果不足惜懊悯,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望苔严。 院中可真熱鬧定枷,春花似錦、人聲如沸届氢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽退子。三九已至岖妄,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間寂祥,已是汗流浹背荐虐。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留丸凭,地道東北人福扬。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像惜犀,于是被迫代替她去往敵國和親铛碑。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內容