-1

I would like to crop an image so its content fills another image and it removes the alpha parts. For example, I have this image as the shape I'm expecting to keep from any other image:

enter image description here

Now if I take this image:

enter image description here

I want to crop it according to the shape image in order to get this:

enter image description here

How can I get this result? Thanks for your help!

Rob
  • 4,123
  • 3
  • 33
  • 53
  • Is the mask you want to use actually a rounded rectangle? If so, you don't need the mask at all, just set `myImageView.layer.cornerRadius = ...` – Connor Neville Mar 16 '18 at 17:10
  • Hi @Connor, it's actually more than a simple rectangle with square radius (I thought of this solution too before), but if you look closely this shape is more like an octagon with slightly rounded corners. – Rob Mar 16 '18 at 17:17
  • 1
    gotcha. This seems to have your answer: https://stackoverflow.com/questions/5757386/how-can-i-mask-a-uiimageview – Connor Neville Mar 16 '18 at 17:24
  • Yeah I got it working thanks to this thread. Thanks! – Rob Mar 16 '18 at 22:04

1 Answers1

0

Following this thread advised by Connor, I got it working with this code:

extension UIImage {

    func maskImage(withMask maskImage: UIImage) -> UIImage {

        let maskRef = maskImage.cgImage

        let mask = CGImage(
            maskWidth: maskRef!.width,
            height: maskRef!.height,
            bitsPerComponent: maskRef!.bitsPerComponent,
            bitsPerPixel: maskRef!.bitsPerPixel,
            bytesPerRow: maskRef!.bytesPerRow,
            provider: maskRef!.dataProvider!,
            decode: nil,
            shouldInterpolate: false)

        let masked = self.cgImage!.masking(mask!)
        let maskedImage = UIImage(cgImage: masked!)

        return maskedImage
    }

}

I also had to switch the white and the alpha parts on the mask image.

Rob
  • 4,123
  • 3
  • 33
  • 53