我正在尝试用我以编程方式创建的图像来为UIImageView设置动画。每当我调用startAnimating()时,我都会得到这个错误
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'我知道当imageView.animationImages中的一个图像为空,而我的图像都不为空时,就会抛出这个错误。
创建一个新的单视图iOS-9应用程序,并将以下代码粘贴到视图控制器的viewDidLoad()中,以查看发生了什么。
super.viewDidLoad()
//Create an imageview and add it to the view
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
imageView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
imageView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true
imageView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
imageView.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
//Create an image
let solidColorFilter = CIFilter(name: "CIConstantColorGenerator")!
solidColorFilter.setValue(CIColor(color: UIColor.redColor()), forKey: "inputColor")
let cropFilter = CIFilter(name: "CICrop")!
cropFilter.setValue(CIVector(CGRect: CGRectMake(0, 0, 300, 300)), forKey: "inputRectangle")
cropFilter.setValue(solidColorFilter.outputImage, forKey: "inputImage")
//Create animation images
var animationImages = [UIImage]()
let hueAdjustFilter = CIFilter(name: "CIHueAdjust")!
hueAdjustFilter.setValue(cropFilter.outputImage, forKey: "inputImage")
for (var i: CGFloat = 0; i < 10; i++) {
hueAdjustFilter.setValue(-CGFloat(M_PI) + CGFloat(i/10.0) * 2.0 * CGFloat(M_PI), forKey: "inputAngle")
let hueAdjustedImage = UIImage(CIImage: hueAdjustFilter.outputImage)
animationImages.append(hueAdjustedImage)
}
print("Break here to inspect images in animationImages array. None are nil")
//Try to animate the images using imageview animationImages
imageView.animationImages = animationImages
imageView.animationDuration = 4.0
imageView.startAnimating() //ERROR THROWN HERE请帮帮我!谢谢!
发布于 2015-08-19 08:12:43
我想通了。当从CIImage创建UIImage时,UIImage的CGImage属性为nil。我猜UIImageView的背景层使用CGImage来呈现它自己。无论如何,要从CIImage获取CGImage,我必须创建一个CIContext,然后调用CIContext.createCGImage:FromRect:,然后使用CGImage创建一个UIImage……以下是代码
//Create a context
let myEAGLContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2)
let options = [kCIContextWorkingColorSpace: NSNull()]
let myContext = CIContext(EAGLContext: myEAGLContext, options: options)
//Create animation images
var animationImages = [UIImage]()
let hueAdjustFilter = CIFilter(name: "CIHueAdjust")!
hueAdjustFilter.setValue(cropFilter.outputImage, forKey: "inputImage")
for (var i: CGFloat = 0; i < 10; i++) {
hueAdjustFilter.setValue(-CGFloat(M_PI) + CGFloat(i/10.0) * 2.0 * CGFloat(M_PI), forKey: "inputAngle")
let hueAdjustedCGImage = myContext.createCGImage(hueAdjustFilter.outputImage, fromRect: CGRectMake(0, 0, 300, 300))
let finalImage = UIImage(CGImage: hueAdjustedCGImage)
animationImages.append(finalImage)
}https://stackoverflow.com/questions/32083961
复制相似问题