UIView.mask设置颜色
问题描述:
我有一个50px的方形UIView,我设置为我的超级视图的蒙版。UIView.mask设置颜色
let squareView = UIView(frame...)
self.view.mask = squareView
的结果是一个50像素正方形透明区域,但它周围的屏蔽区域的颜色是白色总是。如何将透明方形周围的蒙版区域的颜色更改为黑色?
_______________
| |
| <-------------- Masked area that I would like to change the color of
| |
| 000000 |
| 000000 <-------- squareView: becomes transparent as expected
| 000000 |
| 000000 |
| |
| |
| |
|_______________|
答
这是一个代码片段,演示了你想要的效果,我想。您应该可以将它粘贴到新的“单视图”iOS项目中,作为Xcode模板创建的视图控制器的viewDidLoad()
方法。
我需要一些方法来设置掩模视图的内容,而无需创建的UIView
一个子类(因为我懒惰),所以我的示例创建的图像(其alpha通道是1.0与的100×100平方大部分明确的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
}
}
尝试设置视图的层为黑色'self.view.layer.backgroundColor = UIColor.black.CGColor'(键入评论...可能需要一些调整来编译) –
这可能帮助的背景颜色:http://stackoverflow.com/questions/29585943/how-do-i-successfully-set-a-maskview-to-a-uiview – janusbalatbat
@ScottThompson谢谢,但设置主视图的背景颜色没有影响面膜的颜色应用于它。在遮罩视图上设置背景色也不起作用。 – bgolson