在Swift的另一个UIView中使用UIView作为遮罩 [英] Using an UIView as a Mask in another UIView on Swift

查看:505
本文介绍了在Swift的另一个UIView中使用UIView作为遮罩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift在xCode上开发一个应用程序.我的屏幕上有一个动物的图像(出口"backImage"),在该图像上我有一个视图(出口"coverView"),颜色为黑色,覆盖了整个屏幕.到目前为止,您还看不到动物图像,因为"coverView"在它的前面.然后,我有另一个视图(出口"maskView"),该视图较小,并且在大视图"coverView"上.我想要的是使用此"maskView"作为蒙版,因此可以像通过窗口一样查看"backImage".

I am developing an App on xCode with Swift. My screen has an Image of an animal (outlet "backImage"), over this image I have a view (outlet "coverView"), color black, which covers all the screen. So so far you can't see the animal image, because the "coverView" is in front of it. Then I have another view (outlet "maskView") which is smaller and it's over the big view "coverView". What I want is to use this "maskView" as mask and therefor see the "backImage" through it, like a window.

外面有没有人能够弄清楚这一点?

Is there anyone out there able to figure this out?

这是我的屏幕,我想通过较小的白色视图查看大灰色视图后面的女性角色:

Here is my screen, I want to see the woman character behind the big gray view through the smaller white view:

推荐答案

您可以在蒙版视图中设置alpha属性,然后在其他视图的前面添加,例如:

You can set the alpha property from your mask view and add in front of the other view, for instance:

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)


既然您已经用图像编辑了问题,现在我明白了您的需求,那么这就是您如何实现的.


Now that you edited your question with an image, now I see what you need, so here is how you can accomplish that.

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

}

有了此功能,您所需要的只是拥有一个视图并创建一个将在该视图中成为孔的形状,例如:

With this function, all you need is to have a view and create a shape that it's going to be a hole in that view, for instance:

// 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)

这篇关于在Swift的另一个UIView中使用UIView作为遮罩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆