hornobster
hornobster

Reputation: 736

How can I clip a blur UIVisualEffectView with a PNG mask?

I have a blurred UIVisualEffectView and would like to mask it with a PNG UIImage.

I have this code for now, but if I apply the mask, the view doesn't apply the blur effect anymore.

let maskLayer = CAShapeLayer()
maskLayer.contents = UIImage(named: "botnavbarmask")?.cgImage

let maskView = UIView(frame: self.view.frame)
maskView.backgroundColor = UIColor.black
maskView.layer.mask = maskLayer

blurBottom.mask = maskView

Is it even possible to apply a mask to the blur effect?

Any help is appreciated.

Upvotes: 2

Views: 650

Answers (3)

solenoid
solenoid

Reputation: 1022

UIVisualEffectView is kinda wonky. What if you take a snapshot of your effectview, then apply the mask?

func imageFromView(_ view: UIView) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
    view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
    let snapshotImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return snapshotImage
}

I half expect the effectview not to show up, but might be worth a try.

Upvotes: 0

Reinier Melian
Reinier Melian

Reputation: 20804

Use below lines of code,

let maskLayer = CAShapeLayer()
maskLayer.contents = UIImage(named: "icono-menu")?.cgImage

maskLayer.frame = self.blurBottom.bounds
self.blurBottom.layer.masksToBounds = true
self.blurBottom.layer.mask = maskLayer

Hope this helps you

Upvotes: 0

Hashem Aboonajmi
Hashem Aboonajmi

Reputation: 13890

here it is:

let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
let logoView = UIImageView(image: #imageLiteral(resourceName: "logo"))
blurView.mask = logoView

Upvotes: 1

Related Questions