好的,如果您绝对需要自定义相机的 UI 元素,但同时又不想进入 AVAsset 来调出照片库,那么这就是您要做的。
使用 AVFoundation 自定义相机,并将 UIImagePickerController 用于照片库。
在您的自定义相机视图中
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.session = [[AVCaptureSession alloc] init];
[self.session setSessionPreset:AVCaptureSessionPresetPhoto];
AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
if ([self.session canAddInput:self.deviceInput]) {
[self.session addInput:self.deviceInput];
}
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [self layer];
[rootLayer setMasksToBounds:YES];
CGRect frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.width);
[previewLayer setFrame:frame];
[rootLayer insertSublayer:previewLayer atIndex:0];
self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
[self.stillImageOutput setOutputSettings:outputSettings];
[self.session addOutput:self.stillImageOutput];
[self.session startRunning];
}
return self;
}
-(void)takePhoto:(UITapGestureRecognizer *)tap{
[UIView animateWithDuration:0.15
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
self.containerView.frame = CGRectMake(-self.frame.size.width, self.containerView.frame.origin.y, self.containerView.frame.size.width, self.containerView.frame.size.height);
} completion:^(BOOL finished){
if (finished) {
}
}
];
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
videoConnection = connection;
break;
}
}
}
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@"1. newSize.width : %f, newSize.height : %f",image.size.width,image.size.height);
[self.session stopRunning];
[self shouldUploadImage:image];
}
}];
}
-(void)photoAlbumTapped{
NSLog(@"photo album button tapped");
[self.delegate callImagePickerDelegate:self];
}
在 VC 中
-(void)callImagePickerDelegate:(CameraView *)sender{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:picker animated:YES completion:NULL];
}