typealias Filter = (CIImage) -> CIImage
/// 模糊
func blur(radius: Double) -> Filter {
return { image in
let parameters: [String: Any] = [
kCIInputRadiusKey: radius,
kCIInputImageKey: image
]
guard let filter = CIFilter(name: "CIGaussianBlur",
parameters: parameters)
else { fatalError() }
guard let outputImage = filter.outputImage
else { fatalError() }
return outputImage
}
}
/// 颜色叠层
func overlay(color: UIColor) -> Filter {
return { image in
let overlay = generate(color: color)(image).cropped(to: image.extent)
return compositeSourceOver(overlay: overlay)(image)
}
}
/// 生成固定颜色的滤镜
func generate(color: UIColor) -> Filter {
return { _ in
let parameters = [kCIInputColorKey: CIColor(cgColor: color.cgColor)]
// CIConstantColorGenerator: 颜色生成滤镜
guard let filter = CIFilter(name: "CIConstantColorGenerator",
parameters: parameters)
else { fatalError() }
guard let outputImage = filter.outputImage
else { fatalError() }
return outputImage
}
}
/// 合成滤镜
func compositeSourceOver(overlay: CIImage) -> Filter {
return { image in
let parameters = [
kCIInputBackgroundImageKey: image,
kCIInputImageKey: overlay
]
// CISourceOverCompositing: 图像覆盖合成滤镜
guard let filter = CIFilter(name: "CISourceOverCompositing",
parameters: parameters)
else { fatalError() }
guard let outputImage = filter.outputImage
else { fatalError() }
return outputImage.cropped(to: image.extent)
}
}
let url = URL(string: "https://picsum.photos/300/300")!
let image = CIImage(contentsOf: url)!
let radius = 5.0
let color = UIColor.red.withAlphaComponent(0.2)
let blurredImage = blur(radius: radius)(image)
let overlaidImage = overlay(color: color)(blurredImage)
自定义运算符
/// 自定义运算符
infix operator >>>
func >>>(filter1: @escaping Filter, filter2: @escaping Filter) -> Filter {
return { image in filter2(filter1(image)) }
}
let url = URL(string: "https://picsum.photos/300/300")!
let image = CIImage(contentsOf: url)!
let radius = 5.0
let color = UIColor.red.withAlphaComponent(0.2)
let blurAndOverlay = blur(radius: radius) >>> overlay(color: color)
let result = blurAndOverlay(image)
image.png
摘录来自《函数式 Swift》
网友评论