0

I have an image:

enter image description here

That I would like to apply to a UIView to make the waveform (the transparent area) coloured. I have tried the following:

let image = UIImage(named: "waveform")!

let view = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))

let mask = CALayer()
mask.frame = view.bounds
mask.contents = image.cgImage!

view.layer.mask = mask
view.layer.masksToBounds = true
view.backgroundColor = UIColor.green

But this gives me the opposite effect, where the waveform is cut out:

enter image description here

I'd like the outside area of the waveform to be transparent, and the inside to be coloured. I plan to place the UIView on top of another view, so I think it needs to be a mask.

I tried using CIImage to invert the transparent and coloured area as suggested in similar questions:

let cgImage = image.cgImage!
let ciImage = CIImage(cgImage: cgImage)
let filter = CIFilter(name: "CIColorInvert")!
filter.setValue(ciImage, forKey: kCIInputImageKey)

mask.contents = filter.outputImage!.cgImage

...but this resulted in a blank view (transparent background).

Any help would be much appreciated.

Daven
  • 549
  • 4
  • 11
  • i think your looking for this [Reverse a CALayer mask](https://stackoverflow.com/a/42238699/6689101) – zombie Jul 31 '17 at 20:43

1 Answers1

1

Here is one way...

func getImageWithInvertedPixelsOfImage(image: UIImage) -> UIImage {
    let rect = CGRect(origin: CGPoint(), size: image.size)

    UIGraphicsBeginImageContextWithOptions(image.size, false, 2.0)
    UIGraphicsGetCurrentContext()!.setBlendMode(.copy)
    image.draw(in: rect)
    UIGraphicsGetCurrentContext()!.setBlendMode(.sourceOut)
    UIGraphicsGetCurrentContext()!.setFillColor(UIColor.green.cgColor)
    UIGraphicsGetCurrentContext()!.fill(rect)

    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return result!
}

// I named your original image "WaveMask"
let iWave = UIImage(named: "WaveMask")
let invWave = getImageWithInvertedPixelsOfImage(image: iWave!)

// invWave is now Green where it was alpha, and alpha where it was gray
// and can now be used as a mask
DonMag
  • 69,424
  • 5
  • 50
  • 86
  • Thank you! I spent a good few hours trying to solve this, this works perfectly. Time to read up on these functions :) – Daven Jul 31 '17 at 21:14