方法#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開發站點上的complete list of available filters的鏈接。
方法2
找到一個自定義過濾器,如最受好評的答案What is the best Core Image filter to produce black and white effects?。
然後創建一個擴展。以下代碼正文爲信用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
)