我创建了一个自定义的 AVFoundation 相机并使用 @IBDesignable 加载到另一个视图作为子视图,拍摄完图片后我想将其分配给{{1但是,当按下按钮时,自定义摄像机视图(UIImageView
)会崩溃并在屏幕中向上移动,而不是将其分配给UIView
,当自定义摄像机视图加载时会发生这种情况开头,然后当我再次加载自定义相机视图时,它会将图像分配给UIImageView
。
捕获图像方法:
UIImageView
我还尝试了 @IBAction func captureImage(sender: AnyObject) {
if let stillOutput = self.captureImageOutput {
// we do this on another thread so that we don't hang the UI
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
//find the video connection
var videoConnection : AVCaptureConnection?
for connecton in stillOutput.connections {
//find a matching input port
for port in connecton.inputPorts!{
if port.mediaType == AVMediaTypeVideo {
videoConnection = connecton as? AVCaptureConnection
break //for port
}
}
if videoConnection != nil {
break// for connections
}
}
if videoConnection != nil {
stillOutput.captureStillImageAsynchronouslyFromConnection(videoConnection){
(imageSampleBuffer : CMSampleBuffer!, _) in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer)
let pickedImage: UIImage = UIImage(data: imageData, scale: 1.0)!
dispatch_async(dispatch_get_main_queue(), {
self.capturePhoto.image = pickedImage
})
}
}
}
}
}
并且 UIImageView 中没有任何加载,但屏幕不会崩溃。
dispatch_sync
答案 0 :(得分:-1)
我刚试过它,这对我有用(Swift 2.0)
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(frame: self.view.frame)
self.view.addSubview(imageView)
}
func takeImage() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
guard let videoConnection = self.stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) else { return }
guard videoConnection.enabled else { return }
self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) { (buffer: CMSampleBuffer!, error: NSError!) -> Void in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
let image: UIImage = UIImage(data: imageData, scale: 1.0)!
dispatch_async(dispatch_get_main_queue(), {
self.imageView.image = image
print("picture taken")
})
}
}
}
图像已成功拍摄并添加到ViewController中。如果这对你不起作用,也许你可以解释一下你的设置,这样我就可以尝试重现错误/崩溃。