快速为背景添加模糊效果

Posted

技术标签:

【中文标题】快速为背景添加模糊效果【英文标题】:Adding blur effect to background in swift 【发布时间】:2015-09-06 07:48:53 【问题描述】:

我正在为视图控制器设置背景图像。但我也想为这个背景添加模糊效果。我该怎么做?

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

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

我在互联网上找到了模糊图像视图,我该如何在我的背景中实现它?

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

【问题讨论】:

自定义模糊比例请参见此处***.com/a/51406290/7576100 【参考方案1】:

我已经测试了这段代码,它工作正常:

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

【讨论】:

有没有办法改变模糊比例?太模糊了。 改一下UIBlurEffectStyle.Light 或者您可以将 UIVisualEffectView 上的 alpha 设置为小于 1.0。尝试 0.8 或 0.7。 Apple 不建议更改 visualEffectVİew 的 alpha 所有控件都隐藏在这种模糊下。而是 addSubview - 使用 self.view.insertSubview(blurEffectView, at: 0)【参考方案2】:

你可以做 UIImageView 的扩展。

Swift 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()
    
  

斯威夫特 5.0:

import UIKit


extension UIImageView 
    func applyBlurEffect() 
        let blurEffect = UIBlurEffect(style: .light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(blurEffectView)
    

【讨论】:

好主意!难道不能只是 makeBlurImage() 然后用 self 代替 targetImageView 吗? 我不确定,但如果没有传递参数,这段代码可能会崩溃,对吗?这应该有一个“if let tmpTargetImageView = targetImageView ”语句 @RomOne 如果您不提供参数,您只会得到编译错误/构建失败。此外,它可以在没有图像的情况下工作,因此无需打开它;如果您忘记添加图像,测试会告诉您。 如果传递了 nil ImageView,它会崩溃。理想的是@EmanueleFumagalli 使用self 代替targetImageView 的想法,但也可以使用guard 语句并在nil 参数的情况下返回。 最好用模糊的图像描述。好的,谢谢。【参考方案3】:

@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)

【讨论】:

【参考方案4】:

适用于 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)

【讨论】:

【参考方案5】:

你也可以使用CoreImage创建暗效果的模糊图像

    为图片制作快照

    func snapShotImage() -> UIImage 
        UIGraphicsBeginImageContext(self.frame.size)
        if let context = UIGraphicsGetCurrentContext() 
            self.layer.renderInContext(context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        
    
        return UIImage()
    
    

    随心所欲地应用 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()
    
    

【讨论】:

【参考方案6】:

这对我有用 Swift 5

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

【讨论】:

嗨@Marta,你知道如何减少blurredView的容量吗?【参考方案7】:

这个总是保持正确的框架:

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
    

【讨论】:

【参考方案8】:

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

    blurEffectView.backgroundColor = .black
    blurEffectView.alpha = 0.4

【讨论】:

【参考方案9】:

这段代码对我来说很好用! 它适用于 Swift 4.x

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

【讨论】:

【参考方案10】:

在 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)

【讨论】:

【参考方案11】:

找到另一种方式..我使用苹果的 UIImage+ImageEffects.

 UIImage *effectImage = [image applyExtraLightEffect];                        
 self.imageView.image = effectImage;

【讨论】:

【参考方案12】:
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
                    let blurEffectView = UIVisualEffectView(effect: blurEffect)
                    blurEffectView.backgroundColor = .black
                    blurEffectView.alpha = 0.5
                    blurEffectView.frame = topView.bounds
                    if !self.presenting 
                        blurEffectView.frame.origin.x = 0
                     else 
                        blurEffectView.frame.origin.x = -topView.frame.width
                    
                    blurEffectView.frame.origin.x = -topView.frame.width
                    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                    UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) 
                        if !self.presenting 
                            blurEffectView.frame.origin.x = -topView.frame.width
                         else 
                            blurEffectView.frame.origin.x = 0
                        
                        view.addSubview(blurEffectView)
                     completion:  (status) in
                        
                    

【讨论】:

以上是关于快速为背景添加模糊效果的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 7 中将用户背景添加到具有模糊效果的应用程序中?

如何在 SwiftUI 中将模糊效果作为背景?

【iOS开发】生成高斯模糊效果背景

向 SKSpriteNode(或 SKScene)添加背景模糊

背景UIImageView模糊效果(Swift 4)

高斯模糊效果