我想模糊我的iOS应用的整个屏幕,我不能使用UIBlurEffect
因为我希望能够控制模糊性。所以我正在尝试使用CIGaussianBlur
,但我遇到了屏幕边缘的问题。
我正在截取屏幕截图,然后通过CIFilter
CIGaussianBlur
运行它,将CIImage
转换回UIImage
,然后添加新屏幕屏幕上方的图像模糊。
这是我的代码:
let layer = UIApplication.sharedApplication().keyWindow?.layer
UIGraphicsBeginImageContext(view.frame.size)
layer!.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let blurRadius = 5
var ciimage: CIImage = CIImage(image: screenshot)!
var filter: CIFilter = CIFilter(name:"CIGaussianBlur")!
filter.setDefaults()
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(blurRadius, forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
let result = filter.valueForKey(kCIOutputImageKey) as! CIImage!
let cgImage = ciContext.createCGImage(result, fromRect: view.frame)
let finalImage = UIImage(CGImage: cgImage)
let blurImageView = UIImageView(frame: view.frame)
blurImageView.image = finalImage
blurImageView.sizeToFit()
blurImageView.contentMode = .ScaleAspectFit
blurImageView.center = view.center
view.addSubview(blurImageView)
以下是我看到的内容:
除边缘外,它看起来几乎是正确的。似乎模糊度从模糊半径到边缘起飞。我尝试使用上下文大小,但似乎无法使其工作。
如何让模糊一直到边缘?
答案 0 :(得分:12)
这种情况正在发生,因为高斯模糊滤镜会对图像边缘外的像素进行采样。但是因为没有像素,你会得到这个奇怪的人工制品。您可以使用"CIAffineClamp"
过滤器在所有方向上无限地“扩展”您的图像。
请参阅此回答https://stackoverflow.com/a/18138742/762779
我尝试使用链式'CIAffineClamp->运行代码CIGaussianBlur'过滤并获得了良好的效果。
let layer = UIApplication.sharedApplication().keyWindow?.layer
UIGraphicsBeginImageContext(view.frame.size)
layer!.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let blurRadius = 5
let ciimage: CIImage = CIImage(image: screenshot)!
// Added "CIAffineClamp" filter
let affineClampFilter = CIFilter(name: "CIAffineClamp")!
affineClampFilter.setDefaults()
affineClampFilter.setValue(ciimage, forKey: kCIInputImageKey)
let resultClamp = affineClampFilter.valueForKey(kCIOutputImageKey)
// resultClamp is used as input for "CIGaussianBlur" filter
let filter: CIFilter = CIFilter(name:"CIGaussianBlur")!
filter.setDefaults()
filter.setValue(resultClamp, forKey: kCIInputImageKey)
filter.setValue(blurRadius, forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
let result = filter.valueForKey(kCIOutputImageKey) as! CIImage!
let cgImage = ciContext.createCGImage(result, fromRect: ciimage.extent) // changed to ciiimage.extend
let finalImage = UIImage(CGImage: cgImage)
let blurImageView = UIImageView(frame: view.frame)
blurImageView.image = finalImage
blurImageView.sizeToFit()
blurImageView.contentMode = .ScaleAspectFit
blurImageView.center = view.center
view.addSubview(blurImageView)