I’m trying to apply this mask to the original image
Notice there are some grey areas, I want to keep everything except PURE black.
I’ve found this code
func maskImage(image: UIImage, mask: UIImage) -> UIImage {
let imageReference = (image.cgImage)!
let maskReference = (mask.cgImage)!
let imageMask = CGImage(
maskWidth: maskReference.width
, height: maskReference.height
, bitsPerComponent: maskReference.bitsPerComponent
, bitsPerPixel: maskReference.bitsPerPixel
, bytesPerRow: maskReference.bytesPerRow
, provider: maskReference.dataProvider!
, decode: nil
, shouldInterpolate: true
)
return (UIImage(cgImage: (imageReference.masking(imageMask!))!))
}
But it does the opposite, it removes all white pixels instead.
2
Answers
This code creates a new
CGContext
specifically for the mask image and sets the color space to grayscale (CGColorSpaceCreateDeviceGray()
) to ensure that only black pixels are treated as opaque. TheCGImageAlphaInfo.none
parameter is used to specify that the mask image has no alpha channel.By drawing the
maskReference
into thecontext
, the mask is created with the desired behavior of keeping all non-black pixels. Then, themaskImage
is used to mask theimageReference
, resulting in an image with the desired effect.Make the mask inverted before applying it like:
Using this simple extension:
By the way, I suggest inverting the mask outside the code for better performance if possible