這是一個代碼片段,演示了你想要的效果,我想。您應該可以將它粘貼到新的「單視圖」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