起初我想为我的近似英语道歉。
我使用 swift 开发一个 Iphone 项目。
在我的项目中,我有 3 个 View ,其中一个我放了一个摄像头 View (后置摄像头),就像 Snapchat 菜单一样。当我双击时,我希望它切换到前置摄像头。
我在我的代码中添加了一个 Tap 手势识别器,但我不知道如何在其中初始化我的前置摄像头。
这是完整的代码。 如果您需要更多信息,请告诉我!谢谢。
import UIKit
import AVFoundation
class View2: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
@IBAction func DoubleTap(sender: UITapGestureRecognizer) {
}
@IBOutlet var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
// Déclaration Caméra frontale
let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input: AVCaptureDeviceInput!
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let error1 as NSError {
error = error1
input = nil
}
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
}
最佳答案
可能是这个帮助
- (AVCaptureDevice *)showFrontCamera {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == AVCaptureDevicePositionFront) {
return device;
}
}
return nil;
}
这是返回前置摄像头 View 的函数。双击时调用此函数进行切换
AVCaptureDevice *device = [self showFrontCamera];
我有 Objective-c 的代码,也许你可以根据需要将它转换成 swift。
关于ios - 双击时如何切换到前置摄像头(SWIFT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303279/