方法#1
使用 Alamofireimage 的 "imageWithAppliedCoreImageFilter" UIImage 扩展。但由于某种原因,他们不提供对这个过滤器选项的简单协议访问,所以让我们创建一个......
public struct CoreImageFilter: ImageFilter {
let filterName: String
let parameters: [String: AnyObject]
public init(filterName : String, parameters : [String : AnyObject]?) {
self.filterName = filterName
self.parameters = parameters ?? [:]
}
public var filter: UIImage -> UIImage {
return { image in
return image.af_imageWithAppliedCoreImageFilter(self.filterName, parameters: self.parameters) ?? image
}
}
Alamofireimage 用户应该熟悉用法:
let imageView = UIImageView(frame: frame)
let URL = NSURL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!
let color = CIColor(color: UIColor.grayColor()) // or whatever color desired
let intensity = 1.0 // 1.0 is the default, but setting it manually here to allow adjustment
let filter = CoreImageFilter(filterName: "CIColorMonochrome", parameters: ["inputColor": color, "inputIntensity" : intensity])
imageView.af_setImageWithURL(
URL,
placeholderImage: placeholderImage,
filter: filter
)
如果您对 CIColorMonochrome 过滤器不满意(我不满意),这里有一些其他选项...
let filter = CoreImageFilter(filterName: "CIPhotoEffectTonal", parameters: nil)
或者
let filter = CoreImageFilter(filterName: "CIPhotoEffectNoir", parameters: nil)
这是Apple 开发网站上可用过滤器的完整列表的链接。
方法#2
查找自定义滤镜,例如对产生黑白效果的最佳核心图像滤镜是什么?.
然后创建一个扩展。将以下代码的主体归功于Shmidt和DerGote。
extension UIImage {
public func ff_imageFilteredToGrayScale() -> UIImage? {
let context = CIContext(options: nil)
let ciImage = CoreImage.CIImage(image: self)!
// Set image color to b/w
let bwFilter = CIFilter(name: "CIColorControls")!
bwFilter.setValuesForKeysWithDictionary([kCIInputImageKey:ciImage, kCIInputBrightnessKey:NSNumber(float: 0.0), kCIInputContrastKey:NSNumber(float: 1.1), kCIInputSaturationKey:NSNumber(float: 0.0)])
let bwFilterOutput = (bwFilter.outputImage)!
// Adjust exposure
let exposureFilter = CIFilter(name: "CIExposureAdjust")!
exposureFilter.setValuesForKeysWithDictionary([kCIInputImageKey:bwFilterOutput, kCIInputEVKey:NSNumber(float: 0.7)])
let exposureFilterOutput = (exposureFilter.outputImage)!
// Create UIImage from context
let bwCGIImage = context.createCGImage(exposureFilterOutput, fromRect: ciImage.extent)
let resultImage = UIImage(CGImage: bwCGIImage, scale: 1.0, orientation: self.imageOrientation)
return resultImage
}
}
和结构...
public struct GrayScaleFilter: ImageFilter {
public init() {
}
public var filter: UIImage -> UIImage {
return { image in
return image.ff_imageFilteredToGrayScale() ?? image
}
}
}
最后,使用...
let imageView = UIImageView(frame: frame)
let URL = NSURL(string: "https://httpbin.org/image/png")!
let placeholderImage = UIImage(named: "placeholder")!
let filter = GrayScaleFilter()
imageView.af_setImageWithURL(
URL,
placeholderImage: placeholderImage,
filter: filter
)