I am trying to set the AVFoundation camera size based on my UIImageView (selectedImage) size like this:
self.sess = [AVCaptureSession new];
self.snapper = [AVCaptureStillImageOutput new];
self.snapper.outputSettings = @{AVVideoCodecKey: AVVideoCodecJPEG};
self.sess.sessionPreset = AVCaptureSessionPresetPhoto;
[self.sess addOutput:self.snapper];
AVCaptureDevice* cam = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:cam error:nil];
[self.sess addInput:input];
AVCaptureVideoPreviewLayer* lay = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.sess];
lay.videoGravity = AVLayerVideoGravityResizeAspectFill;
lay.frame = selectedImage.frame;
[self.view.layer addSublayer:lay];
In the app, it shows it just fine - 320X320 size, but when I look in the photo gallery, the saved image is longer than a square.
I also tried to remove lay.videoGravity = AVLayerVideoGravityResizeAspectFill;
but then the image in the app is not filling the screen.
How can I set also the shot image size to be what the user sees in the camera with no extra tails?
This is the code that saves the image to gallery:
AVCaptureConnection *vc = [self.snapper connectionWithMediaType:AVMediaTypeVideo];
// deal with image when it arrives
typedef void(^MyBufBlock)(CMSampleBufferRef, NSError*);
MyBufBlock h = ^(CMSampleBufferRef buf, NSError *err) {
NSData* data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:buf];
UIImage* im = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
selectedImage.hidden = NO;
selectedImage.contentMode = UIViewContentModeScaleAspectFill;
selectedImage.clipsToBounds = YES;
selectedImage.image = im;
[self.previewLayer removeFromSuperlayer];
self.previewLayer = nil;
[self.sess stopRunning];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[selectedImage.image CGImage] orientation:(ALAssetOrientation)[selectedImage.image imageOrientation] completionBlock:nil];