簡體   English   中英

如何打開/關閉 iPhone 攝像頭 flash?

[英]How to turn the iPhone camera flash on/off?

如何以編程方式打開/關閉 iPhone 的 LED 攝像頭 flash?

#import <AVFoundation/AVFoundation.h>

...

- (void) turnTorchOn: (bool) on {

    // check if flashlight available
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){

            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                //torchIsOn = YES; //define as a variable/property if you need to know status 
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
                //torchIsOn = NO;            
            }
            [device unlockForConfiguration];
        }
    } }

我將計時器與上面的代碼結合起來。它對我有用......

 - (void)viewDidLoad
        {
         [super viewDidLoad];

         myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self                    selector:@selector(toggleFlashlight) userInfo:nil repeats:YES];
        // Do any additional setup after loading the view from its nib.
        }
       - (void) toggleFlashlight
       {

    // check if flashlight available
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){

            [device lockForConfiguration:nil];
            if (device.torchMode == AVCaptureTorchModeOff) 
            {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                //torchIsOn = YES;
            }
            else 
            {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
               // torchIsOn = NO;            
            }
            [device unlockForConfiguration];
        }
    } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM