有人可以帮我一些事吗?我做了很多研究,一无所获。这是关于掩盖。
我正在使用Swift在xCode上开发一个App。我的屏幕有一个动物图像(插图“backImage”),在这个图像上我有一个视图(插座“coverView”),黑色,覆盖所有屏幕。所以到目前为止你看不到动物图像,因为“coverView”就在它的前面。然后我有另一个视图(插座“maskView”),它更小,它在大视图“coverView”上方。我想要的是使用这个“maskView”作为掩码,因此通过它看到“backImage”,就像一个窗口。
有没有人能够解决这个问题?
这是我的屏幕,我希望通过较小的白色视图看到大灰色视图背后的女性角色:
感谢。
亲切的问候, Renan Gaspar。
答案 0 :(得分:8)
您可以在掩码视图中设置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)
编辑:既然你用图像编辑了你的问题,现在我看到了你需要的东西,所以这就是你如何做到这一点。
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
}
使用此功能,您只需拥有一个视图并创建一个形状,使其成为该视图中的一个洞,例如:
// 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)
答案 1 :(得分:0)
谢谢@Alexandre Lara!你做到了!
以下是解决方案:
@IBOutlet weak var windowView: UIView!
@IBOutlet weak var bigCoverView: UIView!
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
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rectangularHole = windowView.frame.integral
// Set the mask in the created view
setMask(with: rectangularHole, in: bigCoverView!)
}