从相机拍摄图像时闪烁闪光灯

时间:2012-11-26 12:14:53

标签: iphone ipad

我正在使用AVCapture框架工作来设置从相机拍摄照片时闪烁的闪光灯。在这种方法中,我得到闪光灯闪烁效果几秒钟,但随后它会崩溃。

以下是我所做的代码。

-(IBAction) a
{
    _picker = [[UIImagePickerController alloc] init];
    _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    _picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    _picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    _picker.showsCameraControls = YES;
    _picker.navigationBarHidden =YES;
    _picker.toolbarHidden = YES;
    _picker.wantsFullScreenLayout = YES;

    [_picker takePicture];

    // Insert the overlay
    OverlayViewController *overlay = [[OverlayViewController alloc] initWithNibName:@"OverlayViewController" bundle:nil];
    overlay.pickerReference = _picker;
    _picker.cameraOverlayView = overlay.view;
    _picker.delegate = (id)self;

    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(flashLight_On_Off) userInfo:nil repeats:YES];

    [self presentModalViewController:_picker animated:NO];
}

- (void)flashLight_On_Off
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
    {
        if ([device hasFlash] == YES)
        {
            [device lockForConfiguration:nil];
            if (bulPicker == FALSE)
            {
                [device setTorchMode:AVCaptureTorchModeOn];
                bulPicker = TRUE;
            }
            else
            {
                [device setTorchMode:AVCaptureTorchModeOff];
                bulPicker = FALSE;
            }
            [device unlockForConfiguration];
        }

    }
}

有什么问题吗?任何其他方法来获得解决方案?在按下使用按钮之前,我必须在拍摄图像后停止闪烁。

请建议我适当的解决方案。

1 个答案:

答案 0 :(得分:5)

如果我没记错Cocoa命名约定,除了- alloc- copy- mutableCopy之外的任何方法都会返回一个自动释放的对象。在这种情况下,

NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

每秒被调用10次,并且每次被自动释放。这意味着它可能不会立即释放,因此它将开始占用您的RAM,操作系统最终会检测到这一点并终止您的应用程序。

如果您事先知道他们会被大量调用,那么您应该将这些操作包装到自动释放池中。

- (void)toggleFlashlight
{
    @autoreleasepool {
        NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        for (AVCaptureDevice *device in devices)
        {
            if ([device hasFlash]) {
                [device lockForConfiguration:nil];
                if (bulPicker) {
                    [device setTorchMode:AVCaptureTorchModeOff];
                    bulPicker = NO;
                } else  {
                    [device setTorchMode:AVCaptureTorchModeOn];
                    bulPicker = YES;
                }
                [device unlockForConfiguration];
            }
        }
    }
}