我有一个50像素的UIView,我正在设置我的超级视图的面具。
let squareView = UIView(frame...)
self.view.mask = squareView
结果是50px的方形透明区域,但其周围的遮罩区域的颜色始终为白色。如何将透明方块周围遮罩区域的颜色更改为黑色?
_______________
| |
| <-------------- Masked area that I would like to change the color of
| |
| 000000 |
| 000000 <-------- squareView: becomes transparent as expected
| 000000 |
| 000000 |
| |
| |
| |
|_______________|
答案 0 :(得分:4)
这是一段代码片段,可以展示您想要的效果。您应该能够将其粘贴到一个新的单一视图中。 iOS项目作为Xcode模板创建的视图控制器的viewDidLoad()
方法。
我需要一些方法来设置遮罩视图的内容而不创建UIView
的子类(因为我懒惰)所以我的示例创建了一个图像(其alpha通道大部分为1.0)使用100x100平方的透明alpha通道)。我将其设置为蒙版视图的内容。
最后的计时器只是为外部视图循环一堆颜色,因为它很有趣。
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blue
let overallView = UIView(frame: CGRect(x:100, y:100, width:300, height:300))
overallView.backgroundColor = UIColor.green
// Draw a graphics with a mostly solid alpha channel
// and a square of "clear" alpha in there.
UIGraphicsBeginImageContext(overallView.bounds.size)
let cgContext = UIGraphicsGetCurrentContext()
cgContext?.setFillColor(UIColor.white.cgColor)
cgContext?.fill(overallView.bounds)
cgContext?.clear(CGRect(x:100, y:100, width: 100, height: 100))
let maskImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Set the content of the mask view so that it uses our
// alpha channel image
let maskView = UIView(frame: overallView.bounds)
maskView.layer.contents = maskImage?.cgImage
overallView.mask = maskView
self.view.addSubview(overallView)
var hue = CGFloat(0)
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) {
(_) in
let color = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
hue = hue + (1.0/20);
if hue >= 1.0 { hue = 0 }
overallView.backgroundColor = color
}
}