在Swift上的另一个UIView中使用UIView作为掩码

Dev*_*par 7 xcode mask masking uiview swift

有人可以帮我一些事吗?我做了很多研究,一无所获.这是关于掩蔽.

我正在使用Swift在xCode上开发一个App.我的屏幕上有一个动物图像(插图"backImage"),在这个图像上我有一个视图(插座"coverView"),黑色,覆盖所有屏幕.所以到目前为止你看不到动物图像,因为"coverView"就在它的前面.然后我有另一个视图(插座"maskView"),它更小,它在大视图"coverView"上方.我想要的是使用这个"maskView"作为掩码,因此通过它看到"backImage",就像一个窗口.

那里有没有人能够解决这个问题?

这是我的屏幕,我希望通过较小的白色视图看到大灰色视图后面的女人角色:

在此输入图像描述

谢谢.

亲切的问候,Renan Gaspar.

Ale*_*ara 10

您可以alpha从掩码视图设置属性并添加到另一个视图的前面,例如:

let maskView = UIView()
maskView.backgroundColor = UIColor(white: 0, alpha: 0.5) //you can modify this to whatever you need
maskView.frame = CGRect(x: 0, y: 0, width: imageView.frame.width, height: imageView.frame.height)

yourView.addSubview(maskView)
Run Code Online (Sandbox Code Playgroud)

编辑:既然你用图像编辑了你的问题,现在我看到了你需要的东西,所以这就是你如何实现这一目标.

func setMask(with hole: CGRect, in view: UIView){

    // Create a mutable path and add a rectangle that will be h
    let mutablePath = CGMutablePath()
    mutablePath.addRect(view.bounds)
    mutablePath.addRect(hole)

    // Create a shape layer and cut out the intersection
    let mask = CAShapeLayer()
    mask.path = mutablePath
    mask.fillRule = kCAFillRuleEvenOdd

    // Add the mask to the view
    view.layer.mask = mask

}
Run Code Online (Sandbox Code Playgroud)

使用此功能,您只需拥有一个视图并创建一个形状,使其成为该视图中的一个洞,例如:

// Create the view (you can also use a view created in the storyboard)
let newView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
newView.backgroundColor = UIColor(white: 0, alpha: 1)

// You can play with these values and find one that fills your need
let rectangularHole = CGRect(x: view.bounds.width*0.3, y: view.bounds.height*0.3, width: view.bounds.width*0.5, height: view.bounds.height*0.5)

// Set the mask in the created view        
setMask(with: rectangularHole, in: newView)
Run Code Online (Sandbox Code Playgroud)