iPhone4加入了闪光灯,下面就分享一下调用闪光灯的方法:
要加入框架:
#import <AVFoundation/AVFoundation.h>
头文件:
#import "AVCaptureDevice.h"
- (void)loadView
{
[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]autorelease]];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// If torch supported, add button to toggle flashlight on/off
if ([device hasTorch] == YES)
{
flashlightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 120, 320, 98)];
[flashlightButton setBackgroundImage:[UIImage imageNamed:@"TorchOn.png"]forState:UIControlStateNormal];
[flashlightButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[[self view] addSubview:flashlightButton];
}
}
- (void)buttonPressed:(UIButton *)button
{
if (button == flashlightButton)
{
if (flashlightOn == NO)
{
flashlightOn = YES;
[flashlightButton setBackgroundImage:[UIImage imageNamed:@"TorchOff.png"] forState:UIControlStateNormal];
}
else
{
flashlightOn = NO;
[flashlightButton setBackgroundImage:[UIImage imageNamed:@"TorchOn.png"]forState:UIControlStateNormal];
}
[self toggleFlashlight];
}
}
- (void)toggleFlashlight
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device.torchMode == AVCaptureTorchModeOff)
{
// Create an AV session
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// Create device input and add to current session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
[session addInput:input];
// Create video output and add to current session
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
// Start session configuration
[session beginConfiguration];
[device lockForConfiguration:nil];
// Set torch to on
[device setTorchMode:AVCaptureTorchModeOn];
[device unlockForConfiguration];
[session commitConfiguration];
// Start the session
[session startRunning];
// Keep the session around
[self setAVSession:session];
[output release];
}
else
{
[AVSession stopRunning];
[AVSession release], AVSession = nil;
}
}
本文介绍如何在iPhone4上通过编程方式调用闪光灯功能。主要步骤包括引入必要的框架和头文件,检查设备是否支持闪光灯,并创建按钮来控制闪光灯的开关状态。
1949

被折叠的 条评论
为什么被折叠?



