Skip to content

Instantly share code, notes, and snippets.

@darrarski
Last active April 23, 2024 08:32
Show Gist options
  • Save darrarski/29a2a4515508e385c90b3ffe6f975df7 to your computer and use it in GitHub Desktop.
Save darrarski/29a2a4515508e385c90b3ffe6f975df7 to your computer and use it in GitHub Desktop.
UIVisualEffectView subclass that allows to customise effect intensity
import UIKit
final class CustomIntensityVisualEffectView: UIVisualEffectView {
/// Create visual effect view with given effect and its intensity
///
/// - Parameters:
/// - effect: visual effect, eg UIBlurEffect(style: .dark)
/// - intensity: custom intensity from 0.0 (no effect) to 1.0 (full effect) using linear scale
init(effect: UIVisualEffect, intensity: CGFloat) {
theEffect = effect
customIntensity = intensity
super.init(effect: nil)
}
required init?(coder aDecoder: NSCoder) { nil }
deinit {
animator?.stopAnimation(true)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
effect = nil
animator?.stopAnimation(true)
animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [unowned self] in
self.effect = theEffect
}
animator?.fractionComplete = customIntensity
}
private let theEffect: UIVisualEffect
private let customIntensity: CGFloat
private var animator: UIViewPropertyAnimator?
}
@Rotemy
Copy link

Rotemy commented Aug 14, 2018

Working perfectly!

@muratyasarr
Copy link

Thanks dude.

@Hejianghao
Copy link

it doesn't work when use it in a cell of collection view! when you scroll the collection view, it performs like the intensity is useless.

@darrarski
Copy link
Author

it doesn't work when use it in a cell of collection view! when you scroll the collection view, it performs like the intensity is useless.

Hey @Hejianghao could you be more specific about the issue? If you share an example of code that does not work like expected, maybe I would be able to help you.

@Hejianghao
Copy link

Hejianghao commented Apr 16, 2020

it doesn't work when use it in a cell of collection view! when you scroll the collection view, it performs like the intensity is useless.

Hey @Hejianghao could you be more specific about the issue? If you share an example of code that does not work like expected, maybe I would be able to help you.

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

  private let reuseIdentify = "cell"
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let itemW = (self.view.frame.size.width - 15) / 2;
    let layout = UICollectionViewFlowLayout.init();
    layout.itemSize = CGSize.init(width: itemW, height: itemW);
    layout.minimumInteritemSpacing = 5;
    layout.sectionInset = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
    layout.minimumLineSpacing = 5;
    let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout);
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.backgroundColor = UIColor.white
    collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentify)
    
    self.view.addSubview(collectionView);
    
  }
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100;
  }
  
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1;
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentify, for: indexPath) as! MyCollectionViewCell;
    
    return cell;
  }


}

class MyCollectionViewCell: UICollectionViewCell {
  
  var imageView: UIImageView!
  var effectView: UIVisualEffectView!
  
  
  override init(frame: CGRect) {
    super.init(frame: frame);
    
    self.imageView = UIImageView.init(frame: self.bounds)
    self.imageView.image = UIImage.init(named: "test")
    self.addSubview(self.imageView)
    
    let effect = UIBlurEffect.init(style: UIBlurEffect.Style.light)
    let effectView = CustomIntensityVisualEffectView.init(effect: effect, intensity: 0.3)
    effectView.frame = self.bounds
    self.imageView.addSubview(effectView)
    
    
  }
  
  required init?(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
  }
}

image

@darrarski
Copy link
Author

@Hejianghao It looks like when UICollectionViewCell is reused, something strange is going on with UIVisualEffect. Thie quick fix would be to reconfigure the cell every time it's reused:

class MyCollectionViewCell: UICollectionViewCell {

  var imageView: UIImageView!
  var effectView: UIVisualEffectView!

  override init(frame: CGRect) {
    super.init(frame: frame)

    self.imageView = UIImageView.init(frame: self.bounds)
    self.imageView.image = UIImage.init(named: "test")
    self.contentView.addSubview(self.imageView)

    setupBlurEffect()
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override func prepareForReuse() {
    super.prepareForReuse()
    setupBlurEffect()
  }

  private func setupBlurEffect() {
    effectView.removeFromSuperview()
    let effect = UIBlurEffect(style: .light)
    let effectView = CustomIntensityVisualEffectView(effect: effect, intensity: 0.3)
    effectView.frame = imageView.bounds
    imageView.addSubview(effectView)
    self.effectView = effectView
  }
}

While it's not an ideal solution, it works perfectly in your case. I checked it with the code you provided and it behaves correctly, without any issues.

@Hejianghao
Copy link

Thanks, it works. I think the strange thing is the animator.fractionComplete became 1 automatically, when the cell reused.

@mmdock
Copy link

mmdock commented Aug 26, 2020

Doesn't seem to work on iOS 14 :(

@darrarski
Copy link
Author

@mmdock I didn't check it on iOS 14 yet. Could you provide more details?

@orakay
Copy link

orakay commented Dec 9, 2020

On IOS 14.2 this works on initial load of the app. Whenever you switch to another app or home screen and come back, the effect disappears.

@darrarski
Copy link
Author

@orakay thanks for reporting. I have updated the gist, and it should now work correctly on iOS 14.2. I am not sure about the performance, though, as it recreates the UIViewPropertyAnimator every time the view is drawn. However, I used this approach in SwiftUI and didn't notice any performance issues.

@orakay
Copy link

orakay commented Dec 9, 2020

@orakay thanks for reporting. I have updated the gist, and it should now work correctly on iOS 14.2. I am not sure about the performance, though, as it recreates the UIViewPropertyAnimator every time the view is drawn. However, I used this approach in SwiftUI and didn't notice any performance issues.

Thanks for such a quick solution. It works without any performance issue.

@mokai
Copy link

mokai commented Dec 28, 2020

cool

@MonteMango
Copy link

great

@tallot13
Copy link

ios 14.5 from background - effect reset

@billidani7
Copy link

In order to solve the foreground/background issues try setting animator?.pausesOnCompletion = true inside func draw(_ rect: CGRect) after animator = UIViewPropertyAnimator(.....

@dafurman
Copy link

dafurman commented Jun 28, 2022

Just as a heads up, this code has trouble with UITests.

Setting fractionComplete on an animator and not stopping the animation essentially indicates to the test runner that animations haven't settled, which results in tests hanging for long periods of time, showing the following message in the console:
Wait for <myAppIdentifier> to idle

From the docs on fractionComplete:

Changing the value of this property on an inactive animator moves it to the active state.

There's a bit more info on this here that I found helpful in solving this code's behavior with UITests:
https://diggingdeveloper.blog/2022/01/21/xcode-ui-tests-infinite-wait-for-app-to-idle/

As a workaround, you could choose to disable this code with a custom environment variable like isUITesting.

@tiskender2
Copy link

tiskender2 commented Jan 19, 2024

override func draw(_ rect: CGRect) {
    super.draw(rect)
    effect = nil
    animator?.stopAnimation(true)
    animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [unowned self] in
      self.effect = theEffect
    }
    animator?.fractionComplete = customIntensity
    DispatchQueue.main.async { [weak self] in
            self?.animator.stopAnimation(true)
            self?.animator.finishAnimation(at: .current)
        }
  }

for cells and view states, you can finish animation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment