使用图层蒙版使UIView的部分透明?

我有一个UIViewController的背景色为self.view红色。 我想把一个UIImageView放在屏幕的中心。 UIImageView显示覆盖整个屏幕,其背景颜色应该是蓝色的。 作为面具时,中央应该有一个100 x 100的图像。 图像是一个PNG透明和不透明的部分。 使用这个图像作为蒙版,背景应该通过这个PNG的非透明部分可见。 它应该是这样的:

在这里输入图像说明

这里是一个演示如何在应用程序中看起来。

这是我做的:

 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) 

结果如下:

在这里输入图像说明

我想要完全相反。 图像应该在大小100×100的中心。图像的不透明部分应该是后面的视图(在这种情况下为红色)的遮罩。 屏幕的其余部分应该用蓝色覆盖。

编辑: 这是我使用的图像。

我怎样才能做到这一点?

你能分享你的形象吗?

编辑:

看完演示代码后。 你的方法不会像以前一样工作。 他的背景是一个形象。

尝试以下操作:

1-在你的应用程序委托使窗口背景颜色为蓝色。

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

将您的代码replace为以下内容:

 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!