Use Layer Mask to make parts of the UIView transpa

2019-05-29 11:42发布

问题:

I have a UIViewController with a background color red of its self.view. I want to place a UIImageView in the center of the screen. The UIImageView show cover the entire screen and its background color should be blue. There should be a 100 x 100 image in the center when acts as mask. The image is a png with transparent and non transparent parts. Using this image as mask the background should be visible through the non transparent parts of this png. It should look like this:

Here is a demo how this looks in an application.

Here is what I did:

self.view.backgroundColor = UIColor.redColor()
let imageView = UIImageView(frame: self.view.frame)
imageView.backgroundColor = UIColor.blueColor()
let maskImage: UIImage = UIImage(named: "twitterIcon")!
mask = CALayer()
mask?.contents = maskImage.CGImage
mask?.contentsGravity = kCAGravityResizeAspect
mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
mask?.position = CGPoint(x: imageView.frame.size.width/2, y: imageView.frame.size.height/2)
imageView.layer.mask = mask!
self.imageView = imageView
self.view.addSubview(imageView)

And here is the result:

I want to achieve exactly the opposite. The image should be in the center of size 100 x 100. The non transparent part of the image should be the mask which should the view behind (red in this case). The rest of the screen should be covered with blue.

Edit: Here is the image I use.

How can I do that?

回答1:

Can you share your image?

EDIT:

After looking at the demo code. Your approach will not work as the same. His background is an image.

Try the following:

1- In your App Delegate make the window background colour blue.

self.window?.backgroundColor = UIColor.blueColor()

Replace your code with the following:

self.view.backgroundColor = UIColor.redColor()
    let maskImage: UIImage = UIImage(named: "twitterIcon")!
    mask = CALayer()
    mask?.contents = maskImage.CGImage
    mask?.contentsGravity = kCAGravityResizeAspect
    mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
    mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    mask?.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height/2)
    self.view.layer.mask = mask!