我有一个自定义相机视图控制器,使用AVFoundation捕获静态图像,你可以在这里看到:
我的问题是一旦我捕获了一张图片,方向总是横向的,你可以在这里看到
我的代码如下:
var captureInput: AVCaptureInput?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
var currentDevice: AVCaptureDevice?
var currentLayer: AVCaptureVideoPreviewLayer?
@IBAction func captureButtonTap(sender: UIButton) {
if(!capturingPhoto){
capturingPhoto = true
if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
self.stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var image = UIImage(data: imageData)
var imageWidth = image?.size.width
var cropRect = CGRect(x: 0, y: 0, width: imageWidth!, height: imageWidth!)
var imageRef: CGImageRef = CGImageCreateWithImageInRect(image!.CGImage, cropRect)
var croppedImage: UIImage = UIImage(CGImage: imageRef)!
self.imagePreview.image = croppedImage
self.image = croppedImage
self.switchModeToPreview()
}
})
}
}
}
}
func initCameraSession(){
configureDevice()
NSLog(String(selectedCamera))
captureSession = AVCaptureSession()
captureSession!.sessionPreset = AVCaptureSessionPresetPhoto
if(selectedCamera == 0){
var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
currentDevice = backCamera
}else if(selectedCamera == 1){
var frontCamera = frontCameraIfAvalible()
currentDevice = frontCamera
}
if(currentDevice == nil){
NSException(name: "Error", reason: "Device Has No Camera.", userInfo: nil)
}
updateButtons()
var error: NSError?
var input = AVCaptureDeviceInput(device: currentDevice, error: &error)
if error == nil && captureSession!.canAddInput(input) {
captureSession!.addInput(input)
captureInput = input
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession!.canAddOutput(stillImageOutput) {
captureSession!.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraPreview.layer.addSublayer(previewLayer)
previewLayer?.frame = CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.width + 139)
if(currentLayer != nil){
currentLayer!.removeFromSuperlayer()
}
currentLayer = previewLayer!
captureSession!.startRunning()
}
}
}
请注意,我有意留下了一些代码。如果您需要更多信息,请提出要求。感谢您的帮助。