在一些應用中,我們需要用到iOS設備的攝像頭進行拍照,視頻。並且從相冊中選取我們需要的圖片或者視頻。
關於iOS攝像頭和相冊的應用,可以使用UIImagePickerController類來完成控制。
UIImagePickerController 這個類可以為大家提供照相的功能,以及圖片,視頻浏覽的功能。
檢查硬件是否安裝有攝像頭或者允許操作相冊
代碼如下:
#pragma mark - 攝像頭和相冊相關的公共類
// 判斷設備是否有攝像頭
- (BOOL) isCameraAvailable{
return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
// 前面的攝像頭是否可用
- (BOOL) isFrontCameraAvailable{
return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}
// 後面的攝像頭是否可用
- (BOOL) isRearCameraAvailable{
return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
調用攝像頭
代碼如下:
- (BOOL) hasMultipleCameras {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
if (devices != nil && [devices count] > 1) return YES;
return NO;
}
- (AVCaptureDevice *)cameraWithPosition : (AVCaptureDevicePosition) position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices )
if ( device.position == position )
return device;
return nil ;
}
- (void) swapFrontAndBackCameras {
//check for available cameras!
if (![self hasMultipleCameras]) return;
//assumes session is running
NSArray *inputs = self.captureSession.inputs; //should only be one value!
for ( AVCaptureDeviceInput *captureDeviceInput in inputs ) {
AVCaptureDevice *device = captureDeviceInput.device ;
if ( [device hasMediaType:AVMediaTypeVideo ] ) {
AVCaptureDevicePosition position = device.position ;
AVCaptureDevice *newCamera = nil ;
AVCaptureDeviceInput *newInput = nil ;
if (position == AVCaptureDevicePositionFront)
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
else
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
[self initializeCaptureDevice:newCamera];
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
// beginConfiguration ensures that pending changes are not applied immediately
[self.captureSession beginConfiguration ];
[self.captureSession removeInput:captureDeviceInput]; //remove current
[self.captureSession addInput:newInput]; //add new
// Changes take effect once the outermost commitConfiguration is invoked.
[self.captureSession commitConfiguration];
break ;
}
}
}
上面的代碼是使用前置攝像頭和後置攝像頭!