Masking an image in Swift using CALayer and UIImage

前端 未结 1 1834
生来不讨喜
生来不讨喜 2020-12-06 13:29

I\'m programming in Swift. I want to mask an image using CALayer and UIImage. I\'m creating my mask image programmatically. The created mask image is a UIImage and works

相关标签:
1条回答
  • 2020-12-06 14:20

    Unfortunately you've asked your question rather badly - you have not said what it is that you are actually trying to do! It looks, however, as if you might be trying to punch a rectangular hole in your image view using a mask. If so, your code has at least three huge flaws.

    • One reason your code is not working is that a mask is based on transparency, not on color. You are using an opaque white and an opaque black, which are both opaque, so there is no difference there. You need your two colors to be like this:

       var color = UIColor(white: 1.0, alpha: 1.0)
      // ... and then, later ...
      color = UIColor(white: 1.0, alpha: 0.0)
      
    • The second problem is that your layer has no size. You need to give it one:

      var maskLayer = CALayer()
      maskLayer.frame = CGRectMake(
          0, 0, self.imageView.bounds.width, self.imageView.bounds.height)
      
    • The third and biggest problem is that your mask image is never getting into your mask layer, because you have forgotten to extract its CGImage:

      maskLayer.contents = maskImage.CGImage
      

    That last one is really the killer, because if you set the contents to a UIImage without extracting its CGImage, the image fails silently to get into the layer. There is no error message, no crash - and no image.

    Making those three corrections in your code, I was able to make the mask punch a rectangular hole in an image. So if that's your purpose, those changes will achieve it.

    0 讨论(0)
提交回复
热议问题