我試圖捕獲圖像,並在按「myButton」時將其保存到變量中。我該怎麼辦?使用AVFoundation捕獲當前攝像頭圖像
我的代碼如下:
import UIKit
import AVFoundation
import MobileCoreServices
class ViewController: UIViewController {
let captureSession = AVCaptureSession()
var previewLayer : AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice?
@IBOutlet var myTap: UITapGestureRecognizer!
@IBOutlet weak var myButton: UIButton!
@IBAction func shotPress(sender: UIButton) {
//Save image to variable somehow
})
var stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession.canAddOutput(stillImageOutput) {
captureSession.addOutput(stillImageOutput)
}
}
override func viewDidLoad() {
super.viewDidLoad()
captureSession.sessionPreset = AVCaptureSessionPresetHigh
let devices = AVCaptureDevice.devices()
for device in devices {
if (device.hasMediaType(AVMediaTypeVideo)) {
if(device.position == AVCaptureDevicePosition.Back) {
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
beginSession()
}
}
}
}
}
func updateDeviceSettings(focusValue : Float, isoValue : Float) {
if let device = captureDevice {
if(device.lockForConfiguration(nil)) {
device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
device.unlockForConfiguration()
}
}
}
func beginSession() {
var err : NSError? = nil
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: \(err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer)
self.view.bringSubviewToFront(myButton)
previewLayer?.frame = self.view.layer.frame
captureSession.startRunning()
}
}
什麼你基本上做的是試圖抓住這個形象samplebuffer。你可以通過在AVCaptureStillImageOutput上調用'func captureStillImageAsynchronouslyFromConnection(_connection:AVCaptureConnection!,completionHandler handler:((CMSampleBuffer!,NSError!) - > Void)!)'來實現。通過一個完成處理程序,在其中你會做你想要的圖像。 – Jan