update: 2012/02/27
reference: The iOS 5 Developer's Cookbook
A. 建立助手類別
Xcode > File > New > New File...
iOS > Cocoa Touch > Objective-C class > Next
Class: Filter4CamHelper
Subclass of: NSObject
> Next > Create
B. 查詢與取得相機
1. 開啓 Filter4CamHelper.h 檔案, 修改如下:
#import <Foundation/Foundation.h>
//@add
#import <AVFoundation/AVFoundation.h>
@interface Filter4CamHelper : NSObject
{
}
//@add for Available Cameras
+ (int)numberOfCameras; // 相機的數目
+ (BOOL)backCameraAvailable; // 後置相機是否可用
+ (BOOL)frontCameraAvailable; // 前置相機是否可用
+ (AVCaptureDevice *)backCamera; // 後置相機
+ (AVCaptureDevice *)frontCamera; // 前置相機
@end
2. 開啓 Filter4CamHelper.m 檔案, 修改如下:
#import "Filter4CamHelper.h"
#pragma mark Filter4Cam Helper
@implementation Filter4CamHelper
//@add for Available Cameras
#pragma mark Available Cameras
//@add:相機的數目
+ (int)numberOfCameras
{
return [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo].count;
}
//@add:後置相機是否可用
+ (BOOL)backCameraAvailable
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in videoDevices)
if (device.position == AVCaptureDevicePositionBack) return YES;
return NO;
}
//@add:前置相機是否可用
+ (BOOL)frontCameraAvailable
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in videoDevices)
if (device.position == AVCaptureDevicePositionFront) return YES;
return NO;
}
//@add:後置相機
+ (AVCaptureDevice *)backCamera
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in videoDevices)
if (device.position == AVCaptureDevicePositionBack) return device;
return [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
//@add:前置相機
+ (AVCaptureDevice *)frontCamera
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in videoDevices)
if (device.position == AVCaptureDevicePositionFront) return device;
return [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
@end
----------------------------------------------------------------------------------
C. 測試
1. 開啓 ViewController.h 檔案, 修改如下:
#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
//@add
#import "Filter4CamHelper.h"
....
//@add for test
- (void)helperTest;
@end
2. 開啓 ViewController.m 檔案, 修改如下:
#import "ViewController.h"
....
#pragma mark Test
//@add
- (void)helperTest
{
NSLog(@"numberOfCameras = %d", [Filter4CamHelper numberOfCameras]);
NSLog(@"backCameraAvailable = %@", [Filter4CamHelper backCameraAvailable] ? @"YES" : @"NO");
NSLog(@"frontCameraAvailable = %@", [Filter4CamHelper frontCameraAvailable] ? @"YES" : @"NO");
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//@add:helper Test
[self helperTest];}
....
2. 編譯並執行:
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。