1

I have a UIImageView (self.previewImage) in a view that is being used as a preview window for the front facing camera of an iPad. It is square (768x768) and centered in the view. When I grab frames from the camera to save, I end up cropping the full rectangular frame into a square by cutting out a square that is aligned with the TOP of the frame (in portrait mode). No matter what I've tried, the preview window always crops around the CENTER of the frame.

Is there any way to tell the preview to align with the top of the image? If not, is there a way to insert a processing method that can do the crop manually before adding it to the preview?

My original default preview setup was this:

 func setupPreviewLayer() {
    self.previewLayer = AVCaptureVideoPreviewLayer(session: self.cameraSessionController.session)
    self.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.addSublayer(previewLayer)
    previewLayer?.frame = previewImage.frame
}

I've played with self.previewLayer?.bounds and self.previewLayer?.videoGravity without success.

theBaklava
  • 33
  • 6

2 Answers2

0

I actually just dealt with this problem in my app. The problem is that aspect fill resizes AND centers the video feed in your previewlayer. What you have to do is crop a square out of the center of the picture you take.

As far as I know, there's no way to "tell" the video feed to align with the top, nor is there a way is add a processing method that crops the video feed before putting it in the preview. You have to crop the image after you take the picture.

user2320861
  • 1,391
  • 2
  • 11
  • 28
  • Bummer. I was hoping I just didn't know of some magical configuration. But apps that provide a real-time preview of a video with a filter applied have to be doing something to the stream before it gets previewed, or do you have to manually create a preview by grabbing frames, modifying, and setting a UIImageView? – theBaklava Apr 09 '15 at 21:26
  • You might start here: http://stackoverflow.com/questions/5156872/how-to-apply-filters-to-avcapturevideopreviewlayer – user2320861 Apr 09 '15 at 21:33
0

Good pointer. GPUImage filter was able to do this easily.

https://github.com/BradLarson/GPUImage

import UIKit
import GPUImage

class ViewController: UIViewController {

var videoCamera:GPUImageVideoCamera?
var filter:GPUImageCropFilter?

override func viewDidLoad() {
    super.viewDidLoad()

    videoCamera = GPUImageVideoCamera(sessionPreset: AVCaptureSessionPreset640x480, cameraPosition: .Front)
    videoCamera!.outputImageOrientation = .Portrait;
    filter = GPUImageCropFilter(cropRegion: CGRect(x: 0.0, y: 0, width: 1, height: 0.75))
    videoCamera?.addTarget(filter)
    filter?.addTarget(self.view as GPUImageView)
    videoCamera?.startCameraCapture()
}

}

theBaklava
  • 33
  • 6