我无法拍摄6张照片并将其存储在对象阵列中以便为它们制作动画。我一直收到错误说:
数组索引超出范围
另外,我意识到由于某种原因,在if语句之外无法识别“image”对象。我做错了什么?
func didPressTakePhoto(){
var picArray: [UIImage] = []
for index in 1...6 {
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProviderCreateWithCFData(imageData)
let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)
let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.hidden = false
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
picArray[index] = image;
}
})
}
}
self.gifView.animationImages = picArray;
self.gifView.animationDuration = 1.0
self.gifView.startAnimating()
}
答案 0 :(得分:1)
picArray
为空,因此您不应使用insert
方法。相反,你必须使用append
方法。
picArray
为空的原因是您在asynchronous
块中插入值。 for循环在插入图像之前完成,因为它不等待异步块完成。
在动画图像视图之前,您必须等待asynchronous
块完成。
您可以使用dispatch_group
func didPressTakePhoto(){
var picArray: [UIImage] = []
let dispatchGroup = dispatch_group_create()
for index in 1...6 {
dispatch_group_enter(dispatchGroup)
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProviderCreateWithCFData(imageData)
let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)
let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.hidden = false
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
picArray.append(image);
}
dispatch_group_leave(dispatchGroup)
})
} else {
dispatch_group_leave(dispatchGroup)
}
}
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()) {
self.gifView.animationImages = picArray;
self.gifView.animationDuration = 1.0
self.gifView.startAnimating()
}
}
希望这有帮助。