如何在Swift中添加半径为2pt的模糊? [英] How can I add blur with 2pt of radius in Swift?
问题描述
我想创建类似的东西
我已经尝试过这个:
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
var blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
view.addSubview(blurEffectView)
但是会产生非常暗的模糊.但是我需要半径为2pt的完全暗的模糊(黑色).
but this creates very dark blur. But I need exactly dark blur(black color) with 2pt of radius.
我可以在Swift中实现吗?
Can I achieve that in Swift?
推荐答案
您无法控制UIVisualEffectView
的模糊半径.通过对要模糊的视图进行快照,然后将CoreImage的"CIGaussianBlur"过滤器应用于该快照,然后将模糊的图像显示在要模糊的视图正上方的UIImageView
中,可以实现所需的功能.使用CIGaussianBlur
,您可以将模糊半径应用于任意长度.
You can't control the radius of the blur of a UIVisualEffectView
. You can achieve what you want by snapshotting the view you want to blur and applying a CoreImage's "CIGaussianBlur" filter to that snapshot then displaying the blurred image in a UIImageView
placed directly above the view you want to blur. With CIGaussianBlur
you can apply a blur radius to an arbitrary length.
您可以在UIView
上使用扩展名,以使其更加方便:
You can use an extension on UIView
to make this more convenient:
extension UIView
{
func snapshotView(scale scale: CGFloat = 0.0, isOpaque: Bool = true) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, opaque, scale)
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func blur(blurRadius blurRadius: CGFloat) -> UIImage?
{
guard let blur = CIFilter(name: "CIGaussianBlur") else { return nil }
let image = self.snapshotView(scale: 1.0, isOpaque: true)
blur.setValue(CIImage(image: image), forKey: kCIInputImageKey)
blur.setValue(blurRadius, forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
let result = blur.valueForKey(kCIOutputImageKey) as! CIImage!
let boundingRect = CGRect(x: 0,
y: 0,
width: frame.width,
height: frame.height)
let cgImage = ciContext.createCGImage(result, fromRect: boundingRect)
return UIImage(CGImage: cgImage)
}
}
然后,您可以添加一个半透明的叠加层来确定模糊的程度,例如:
Then you can add a semi transparent overlay to determine how dark the blur is, for example:
let overlay = UIView()
overlay.frame = view.bounds
overlay.backgroundColor = UIColor(white: 0.0, alpha: 0.30)
viewIWantToBlur.addSubview(overlay)
let image = viewIWantToBlur.blur(blurRadius: 2.0)
imageView.image = image
有关此方法的更多信息和更可靠的工作示例,您可以在此处看到.您应该是注意这是性能密集型.
For more information on this method and a more robust working example you can see here. You should be aware that this is performance intensive.
这篇关于如何在Swift中添加半径为2pt的模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!