0

Ok, Im working in Swift here and there are a lot of answers like this How to use UIVisualEffectView? that talk about how to apply a UIVisualEffectView OVER an image, so that it blurs it like a background.

My problem is I need to have my image, or rather the outline of my image BE the Blur view - meaning I create a blur UIVisualEffectView in the shape of my image so the "color" of the image itself is the blur. An example mockup (pretend that is a blur):

enter image description here

I know you can trace a UIImage into a custom color like this:

func overlayImage(color: UIColor, img: UIImage) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(img.size, false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()

    color.setFill()

    context!.translateBy(x: 0, y: img.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
    context!.draw(img.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return coloredImage!
}

But I cant get my UIImageView to "mask" the blur view and achieve the effect. Right now with this attempt:

var img = UIImageView(image: UIImage(named: "dudeIco"))
        img.frame = CGRect(x: 0, y: 0, width: self.bounds.width * 0.7, height: self.bounds.width * 0.7)
        img.center = CGPoint(x: self.bounds.width/2, y: self.bounds.height/2)
        self.addSubview(img)

        let blur = UIVisualEffectView(effect: UIBlurEffect(style:
            UIBlurEffectStyle.light))
        blur.frame = img.bounds
        blur.isUserInteractionEnabled = false
        img.insertSubview(blur, at: 0)

I just get a blurred square. I need the shape of the image. How can I do this? Is this impossible?

blue
  • 7,175
  • 16
  • 81
  • 179

0 Answers0