import UIKitfunc colorizeImage(greyImage : UIImage,tintcolor : UIcolor) -> UIImage? { let colorMatrixFilter = CIFilter(name: "CIcolorMatrix") var r:CGfloat = 0 var g:CGfloat = 0 var b:CGfloat = 0 var a:CGfloat = 0 tintcolor.getRed(&r,green:&g,blue:&b,Alpha:&a) colorMatrixFilter.setDefaults() colorMatrixFilter.setValue(greyImage,forKey:"inputimage") //kCIInputimageKey) colorMatrixFilter.setValue(CIVector(x:r,y:0,z:0,w:0),forKey:"inputRVector") colorMatrixFilter.setValue(CIVector(x:0,y:g,forKey:"inputGVector") colorMatrixFilter.setValue(CIVector(x:0,z:b,forKey:"inputBVector") colorMatrixFilter.setValue(CIVector(x:0,w:a),forKey:"inputAVector") if let ciImage = colorMatrixFilter.outputimage { return UIImage(CIImage: ciImage); } return nil;}
颜色为UIcolor.orangecolor()(r = 1,g = 0.5,b = 0,a = 1),灰度图像正常,因为它在送到ImageVIEw时可以正确显示.
看起来提供了所有必需的密钥并且密钥分配顺利进行(BTW过滤器检查密钥的有效性,还是采取一切措施?),但是读取’outputimage’属性会产生SIGABRT和以下控制台消息:
2015-05-02 13:04:07.319 MyApp[436:8241] -[UIImage _internalRepresentation]: unrecognized selector sent to instance 0x7fd5b3ca82b02015-05-02 13:04:07.629 MyApp[436:8241] *** Terminating app due to uncaught exception 'NSinvalidargumentexception',reason: '-[UIImage _internalRepresentation]: unrecognized selector sent to instance 0x7fd5b3ca82b0'*** First throw call stack:( 0 CoreFoundation 0x00000001087abf35 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x000000010a56cbb7 objc_exception_throw + 45 2 CoreFoundation 0x00000001087b304d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205 3 CoreFoundation 0x000000010870b27c ___forwarding___ + 988 4 CoreFoundation 0x000000010870ae18 _CF_forwarding_prep_0 + 120 5 CoreImage 0x0000000108bd30fe -[CIcolorMatrix outputimage] + 885 6 MyApp 0x00000001085c182d _TF8MyApp13colorizeImageFTCSo7UIImageCSo7UIcolor_GSqS0__ + 4733 7 MyApp 0x00000001085c2b59解决方法 问题是 CIColorMatrix期望参数inputimage应该是CIImage对象而不是UIImage(greyImage).
更新:Swift 3或更高版本
extension UIImage { func colorized(with color: UIcolor) -> UIImage? { guard let ciimage = CIImage(image: self),let colorMatrix = CIFilter(name: "CIcolorMatrix") else { return nil } var r: CGfloat = 0,g: CGfloat = 0,b: CGfloat = 0,a: CGfloat = 0 color.getRed(&r,green: &g,blue: &b,Alpha: &a) colorMatrix.setDefaults() colorMatrix.setValue(ciimage,forKey: "inputimage") colorMatrix.setValue(CIVector(x: r,y: 0,z: 0,w: 0),forKey: "inputRVector") colorMatrix.setValue(CIVector(x: 0,y: g,forKey: "inputGVector") colorMatrix.setValue(CIVector(x: 0,z: b,forKey: "inputBVector") colorMatrix.setValue(CIVector(x: 0,w: a),forKey: "inputAVector") if let ciimage = colorMatrix.outputimage { return UIImage(ciImage: ciimage) } return nil }}
let profilePicture = UIImage(data: try! Data(contentsOf: URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!))!profilePicture.colorized(with: .orange)总结
以上是内存溢出为你收集整理的ios – 在Swift中使用CIColorMatrix过滤器全部内容,希望文章能够帮你解决ios – 在Swift中使用CIColorMatrix过滤器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)