ios – 全屏高斯模糊

前端之家收集整理的这篇文章主要介绍了ios – 全屏高斯模糊前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想模糊我的iOS应用程序的整个屏幕,我不能使用UIBlurEffect,因为我希望能够控制模糊.所以我正在尝试使用CIGaussianBlur,但是我遇到了屏幕边缘的问题.

我正在截取屏幕截图,然后通过带有CIGaussianBlur的CIFilter运行它,将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)

这是我看到的:

除边缘外,它看起来几乎是正确的.似乎模糊度从模糊半径到边缘起飞.我尝试使用上下文大小,但似乎无法使其工作.

如何让模糊一直到边缘?

解决方法

之所以发生这种情况,是因为高斯模糊滤镜会对图像边缘外的像素进行采样.但是因为没有像素,你会得到这个奇怪的人工制品.您可以使用“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)
原文链接:https://www.f2er.com/iOS/329683.html

猜你在找的iOS相关文章