最近正好有一个项目,很简单,最后动画完成之后会有一个拍照功能,但是要用他们自定义的图片,挤压进行拍照,所以就就要进行自定义这个功能了。
首先自定义拍照我们需要的框架是 AVFoundation,他提供了很多关于和拍照相关的类。
AVCaptureSession:对象来执行输入设备和输出设备之间的数据传递.
AVCaptureDeviceInput:对象是输入流。
AVCaptureStillImageOutput 照片流的输出。
AVCaptureVideoPreviewLayer 预览图层,来显示照相机拍摄到的画面。
现在就开始吧:首先初始化相机
BOOL success = NO;
// 如果该设备的后置摄像头有射光灯
if ([self.backFacingCamera hasFlash])
{
if ([self.backFacingCamera lockForConfiguration:nil])
{
if ([self.backFacingCamera isFlashModeSupported:AVCaptureFlashModeAuto])
{
// 将后置摄像头的闪光灯设为自动模式
[self.backFacingCamera setFlashMode:AVCaptureFlashModeAuto];
}
[self.backFacingCamera unlockForConfiguration];
}
}
// 如果该设备的后置摄像头有电筒
if ([self.backFacingCamera hasTorch])
{
if ([self.backFacingCamera lockForConfiguration:nil])
{
if ([self.backFacingCamera isTorchModeSupported:AVCaptureTorchModeAuto])
{
// 将后置摄像头的电筒设为自动模式
[self.backFacingCamera setTorchMode:AVCaptureTorchModeAuto];
}
[self.backFacingCamera unlockForConfiguration];
}
}
// 初始化输入设备
self.nVideoInput = [[AVCaptureDeviceInput alloc]
initWithDevice:[self backFacingCamera] error:nil];
// AVCaptureDeviceInput *newAudioInput = [[AVCaptureDeviceInput alloc]
// initWithDevice:[self audioDevice] error:nil];
// 设置照片的输出设备
AVCaptureStillImageOutput *newStillImageOutput =
[[AVCaptureStillImageOutput alloc] init];
// 设置输出照片的格式
NSDictionary *outputSettings = [[NSDictionary alloc]
initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey,nil];
[newStillImageOutput setOutputSettings:outputSettings];
// 创建AVCaptureSession
self.captureSession = [[AVCaptureSession alloc] init];
// 将输入、输出设备添加到AVCaptureSession中
if ([self.captureSession canAddInput:_nVideoInput])
{
[self.captureSession addInput:_nVideoInput];
}
if ([self.captureSession canAddOutput:newStillImageOutput])
{
[self.captureSession addOutput:newStillImageOutput];
}
[self setStillImageOutput:newStillImageOutput];
success = YES;
return success;
然后在viewDidLoad中初始化显示图层
if ([self setupSession]) {
self.cameraShowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewWidth, viewHeight)];
// [self.view addSubview:_cameraShowView];
// [_cameraShowView release];
[self.cameraShowView.layer setMasksToBounds:YES];
// 创建摄像头的预览Layer
_previewLayer = [[AVCaptureVideoPreviewLayer alloc]
initWithSession:self.captureSession];
CGRect bounds = _cameraShowView.bounds;
// 设置预览Layer的大小和位置
_previewLayer.frame = bounds;
// 设置预览Layer的缩放方式
[_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
// 将预览Layer添加到预览UIView上
[self.cameraShowView.layer insertSublayer:_previewLayer
below:[[self.cameraShowView.layer sublayers] objectAtIndex:0]];
dispatch_async(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.captureSession startRunning];
});
}
m_bScreen = 1;
NSNotificationCenter *notificationCenter =
[NSNotificationCenter defaultCenter];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[notificationCenter addObserver:self selector:
@selector(deviceOrientationDidChange) name:
UIDeviceOrientationDidChangeNotification object:nil];
self.orientation = AVCaptureVideoOrientationLandscapeRight;
[self performSelector:@selector(addCameraShowViews) withObject:nil afterDelay:1];
延迟添加图层,在做的时候总是打开看见翻转图像,为了缓解,我延时加载这样在我看见的时候就是我刚好需要的方向。
- (void)addCameraShowViews
{
[self.view addSubview:_cameraShowView];
[_cameraShowView release];
_Showbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_Showbtn.frame = CGRectMake((viewWidth - btnWidth), (viewHeight - btnHeight)/2, btnWidth, btnHeight);
[_Showbtn setBackgroundImage:[UIImage imageNamed:@"smoke.png"] forState:UIControlStateNormal];
_Showbtn.backgroundColor = [UIColor redColor];
[_Showbtn addTarget:self action:@selector(captureStillImage) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_Showbtn];
PanBox * pan = [[PanBox alloc] initWithFrame:CGRectMake(0, 0, viewWidth, viewHeight)];
[self.view addSubview:pan];
[pan addPanAction];
[pan release];
pan.panItBlock = ^(void){
[cameView captureStillImage];
};
}
设置摄像头的位置
// 定义一个方法,获取前置或后置的视频设备
- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position
{
// 获取所偶的视频设备
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
// 遍历所有的视频设备
for (AVCaptureDevice *device in devices)
{
// 如果该设备的位置与被查找位置相同,返回该视频设备
if (device.position == position)
{
return device;
}
}
return nil;
}
// 定义获取前置摄像头的方法
- (AVCaptureDevice *) frontFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionFront];
}
// 定义获取后置摄像头的方法
- (AVCaptureDevice *) backFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionBack];
}
最关键的是页面的旋,这里我只是用到了横屏
// 跟踪设备方向的改变,保证视频和相片的方向与设备方向一致
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)
interfaceOrientation duration:(NSTimeInterval)duration
{
// 根据屏幕方向对预览Layer进行旋转,保证预览画面总是与拍照画面一致
switch (interfaceOrientation)
{
case UIInterfaceOrientationLandscapeLeft:
_previewLayer.affineTransform = CGAffineTransformMakeRotation(M_PI_2);
break;
case UIInterfaceOrientationLandscapeRight:
_previewLayer.affineTransform =
CGAffineTransformMakeRotation(M_PI * 3 / 2);
break;
// case UIInterfaceOrientationPortrait:
// _previewLayer.affineTransform = CGAffineTransformMakeRotation(M_PI * 3 / 2);;
break;
default:
break;
}
_previewLayer.frame = self.view.bounds;
}
最关键的拍照,这里要在输出的时候一定要设定输出的方向与拍摄的方向一致,否则有一个方向拍出来是反向的。
[stillImageConnection setVideoOrientation:self.orientation];
- (void)captureStillImage
{
// 获取拍照的AVCaptureConnection
AVCaptureConnection *stillImageConnection = [self
connectionWithMediaType:AVMediaTypeVideo
fromConnections:[[self stillImageOutput] connections]];
if ([stillImageConnection isVideoOrientationSupported])
{
[stillImageConnection setVideoOrientation:self.orientation];
}
// 拍照并保存
[self.stillImageOutput
captureStillImageAsynchronouslyFromConnection:stillImageConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
ALAssetsLibraryWriteImageCompletionBlock completionBlock =
^(NSURL *assetURL, NSError *error)
{
if (error)
{
}
};
// 如果图片缓存不为NULL
if (imageDataSampleBuffer != NULL)
{
NSData *imageData = [AVCaptureStillImageOutput
jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
// 创建ALAssetsLibrary,用于将照片写入相册
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [[UIImage alloc] initWithData:imageData];
_creameImage = [[LionCreameView alloc] initWithFrame:CGRectMake(-30, -30, viewWidth+40, viewHeight+40)];
[_creameImage ProcessingThePictures:image complict:^(UIImage *image) {
[cameView chooseView];
return ;
}];
if (cameView.captureSession) {
[cameView.captureSession stopRunning];
}
[cameView.view addSubview:_creameImage];
[_creameImage release];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:completionBlock];
}
else
{
completionBlock(nil, error);
}
}];
}
这里拍照的功能就完成了。。。。。