技术上准确的答案是CIFilter
需要一个CIImage
。你可以转动一个UIView
into a UIImage
然后将其转换为CIImage
,但所有使用图像作为输入的 CoreImage 过滤器(有些会生成新图像)都使用 CIImage 进行输入和输出。
- 请注意,a 的起源
CIImage
是左下角,不是左上角。基本上Y轴被翻转了。
- 如果您动态使用 CoreImage 滤镜,请学习使用
GLKView
渲染 - 它使用 GPU,其中UIImageView
使用CPU。
- 如果您想测试过滤器,最好使用实际设备。模拟器会给你very表现不佳。我见过一个简单的模糊需要花费近一分钟,而在设备上则只需几分之一秒!
假设你有一个UIView
您希望申请CI照片效果单色 https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/CIPhotoEffectMono到。执行此操作的步骤是:
- 转换
UIView
into a CIImage
.
- 应用过滤器,得到
CIImage
作为输出。
- Use a
CIContext
创建一个CGImage
然后将其转换为UIImage
.
这是一个UIView
将转换视图的扩展and所有它的子视图都变成了UIImage
:
extension UIView {
public func createImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: self.frame.width, height: self.frame.height), true, 1)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
转换一个UIImage
into a CIImage
是一行代码:
let ciInput = CIImage(image: myView.createImage)
这是一个将应用过滤器并返回UIImage
:
func convertImageToBW(image:UIImage) -> UIImage {
let filter = CIFilter(name: "CIPhotoEffectMono")
// convert UIImage to CIImage and set as input
let ciInput = CIImage(image: image)
filter?.setValue(ciInput, forKey: "inputImage")
// get output CIImage, render as CGImage first to retain proper UIImage scale
let ciOutput = filter?.outputImage
let ciContext = CIContext()
let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)
return UIImage(cgImage: cgImage!)
}