快速向背景添加模糊效果


118

我正在设置背景图像以查看控制器。但我也想在此背景上添加模糊效果。我怎样才能做到这一点?

我使用以下代码设置背景:

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "testBg")!)

我在互联网上发现模糊imageview,该如何在我的背景中实现呢?

var darkBlur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
// 2
var blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = imageView.bounds
// 3
imageView.addSubview(blurView)

有关自定义模糊比例的信息,请参见此处stackoverflow.com/a/51406290/7576100
杰克

Answers:


333

我已经测试过此代码,并且可以正常工作:

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

对于Swift 3.0:

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

对于Swift 4.0:

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

在这里您可以看到结果:

模糊的观点

或者,您可以使用以下库:

https://github.com/FlexMonkey/Blurable


5
有没有办法改变模糊比例?太模糊了。
Tolgay Toklar

2
只是改变UIBlurEffectStyle.Light
Dharmesh Kheni 2015年

11
或者,您可以将UIVisualEffectView上的Alpha设置为小于1.0。尝试0.8或0.7。
Duncan C

31
苹果不建议更改visualEffectVİew的Alpha
Tolgay Toklar '16

4
所有控件都被隐藏在这种模糊下。而是使用addSubview-使用self.view.insertSubview(blurEffectView,at:0)
Leonif,

45

您可以扩展UIImageView。

雨燕2.0

import Foundation
import UIKit

extension UIImageView
{
    func makeBlurImage(targetImageView:UIImageView?)
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = targetImageView!.bounds

        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
        targetImageView?.addSubview(blurEffectView)
    }
}

用法:

override func viewDidLoad()
{
    super.viewDidLoad()

    let sampleImageView = UIImageView(frame: CGRectMake(0, 200, 300, 325))
    let sampleImage:UIImage = UIImage(named: "ic_120x120")!
    sampleImageView.image =  sampleImage

    //Convert To Blur Image Here
    sampleImageView.makeBlurImage(sampleImageView)

    self.view.addSubview(sampleImageView)
}

Swift 3扩展

import Foundation
import UIKit

extension UIImageView
{
    func addBlurEffect()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds

        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }
}

用法:

yourImageView.addBlurEffect()

附录:

extension UIView {

  /// Remove UIBlurEffect from UIView
  func removeBlurEffect() {
    let blurredEffectViews = self.subviews.filter{$0 is UIVisualEffectView}
    blurredEffectViews.forEach{ blurView in
      blurView.removeFromSuperview()
    }
  }

7
好主意!难道只是makeBlurImage()然后使用self而不是targetImageView吗?
Emanuele Fumagalli

1
我不确定,但是如果没有传递参数,此代码可能会崩溃?这应该有一个“ if let tmpTargetImageView = targetImageView {}”语句
RomOne

@RomOne如果不提供参数,则只会得到编译错误/构建失败。而且,它可以在没有图像的情况下工作,因此无需拆开包装;测试会显示您是否忘记添加图像。
乔什

关键是如果传递了nil ImageView,它将崩溃。理想的是@EmanueleFumagalli的使用self而不是targetImageView的想法,但是也可以使用保护语句,并在参数为nil的情况下返回。
Uzaak

最好也对图像进行模糊描述。非常感谢。
MRizwan33 '18

13

@AlvinGeorge应该只使用:

extension UIImageView{        
    func blurImage()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds

        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }
}

用法

 blurredBackground.frame = self.view.bounds
 blurredBackground.blurImage()
 self.view.addSubview(self.blurredBackground)

11

对于Swift 3(iOS 10.0和8.0)

var darkBlur:UIBlurEffect = UIBlurEffect()

if #available(iOS 10.0, *) { //iOS 10.0 and above
    darkBlur = UIBlurEffect(style: UIBlurEffectStyle.prominent)//prominent,regular,extraLight, light, dark
} else { //iOS 8.0 and above
  darkBlur = UIBlurEffect(style: UIBlurEffectStyle.dark) //extraLight, light, dark
}
let blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = self.view.frame //your view that have any objects
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurView)

10

您还可以使用CoreImage创建具有暗效果的模糊图像

  1. 为图像制作快照

    func snapShotImage() -> UIImage {
        UIGraphicsBeginImageContext(self.frame.size)
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.renderInContext(context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    
        return UIImage()
    }
  2. 根据需要应用CoreImage滤镜

    private func bluredImage(view:UIView, radius:CGFloat = 1) -> UIImage {
    let image = view.snapShotImage()
    
    if let source = image.CGImage {
        let context = CIContext(options: nil)
        let inputImage = CIImage(CGImage: source)
    
        let clampFilter = CIFilter(name: "CIAffineClamp")
        clampFilter?.setDefaults()
        clampFilter?.setValue(inputImage, forKey: kCIInputImageKey)
    
        if let clampedImage = clampFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
            let explosureFilter = CIFilter(name: "CIExposureAdjust")
            explosureFilter?.setValue(clampedImage, forKey: kCIInputImageKey)
            explosureFilter?.setValue(-1.0, forKey: kCIInputEVKey)
    
            if let explosureImage = explosureFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
                let filter = CIFilter(name: "CIGaussianBlur")
                filter?.setValue(explosureImage, forKey: kCIInputImageKey)
                filter?.setValue("\(radius)", forKey:kCIInputRadiusKey)
    
                if let result = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
                    let bounds = UIScreen.mainScreen().bounds
                    let cgImage = context.createCGImage(result, fromRect: bounds)
                    let returnImage = UIImage(CGImage: cgImage)
                    return returnImage
                }
            }
        }
    }
    return UIImage()
    }

8

这在Swift 5上对我有用

let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)

1
嗨@Marta,您知道如何减少bluredView的容量吗?
天空

5

这总是保持正确的框架:

public extension UIView {

    @discardableResult
    public func addBlur(style: UIBlurEffect.Style = .extraLight) -> UIVisualEffectView {
        let blurEffect = UIBlurEffect(style: style)
        let blurBackground = UIVisualEffectView(effect: blurEffect)
        addSubview(blurBackground)
        blurBackground.translatesAutoresizingMaskIntoConstraints = false
        blurBackground.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        blurBackground.topAnchor.constraint(equalTo: topAnchor).isActive = true
        blurBackground.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        blurBackground.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        return blurBackground
    }
}

3

您应该始终使用.dark作为样式,并添加以下代码以使其看起来很酷

    blurEffectView.backgroundColor = .black
    blurEffectView.alpha = 0.4

1

该代码对我来说很好用!对于Swift 4.x

let blurEffect = UIBlurEffect(style: .ExtraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.view.frame
self.view.insertSubview(blurEffectView, atIndex: 0)


0

在UIView扩展中:

func addBlurredBackground(style: UIBlurEffect.Style) {
    let blurEffect = UIBlurEffect(style: style)
    let blurView = UIVisualEffectView(effect: blurEffect)
    blurView.frame = self.frame
    blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.addSubview(blurView)
    self.sendSubviewToBack(blurView)
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.