2017-09-16 42 views
2

我創建一個覆蓋的模糊視圖與中間明確的矩形剪影。我的代碼到目前爲止已經取得了相反的結果,即在中間有一個模糊切口的clearView。創建一個明確的剪切模糊視圖

我已經改編了以下文章中的步驟,我很感激任何人都可以將我指向正確的方向。

Swift mask of circle layer over UIView

CALayer with transparent hole in it

let blurView = UIVisualEffectView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)) 
blurView.effect = UIBlurEffect(style: UIBlurEffectStyle.dark) 

let scanLayer = CAShapeLayer() 
scanLayer.path = CGPath(rect: scanRect, transform: nil) 

view.addSubview(blurView) 
blurView.layer.addSublayer(scanLayer) 
blurView.layer.mask = scanLayer 
+0

我沒有任何想法......但最後一行不應該存在blurView.layer.mask = scanLayer – Naresh

+0

使用此https://stackoverflow.com/questions/29647792/swift-how-to-create-a-view-with-a-shape-cropped-in-it請參閱DănuţMihai Florian的回答 – Naresh

回答

2

你可以像下面這樣做

let scanLayer = CAShapeLayer() 

    let scanRect = CGRect.init(x: 100, y: 100, width: 200, height: 100) 

    let outerPath = UIBezierPath(rect: scanRect) 

    let superlayerPath = UIBezierPath.init(rect: blurView.frame) 
    outerPath.usesEvenOddFillRule = true 
    outerPath.append(superlayerPath) 
    scanLayer.path = outerPath.cgPath 
    scanLayer.fillRule = kCAFillRuleEvenOdd 
    scanLayer.fillColor = UIColor.black.cgColor 

    view.addSubview(blurView) 
    blurView.layer.mask = scanLayer 
+0

此解決方案工作!但我不明白這個概念。爲什麼需要有superlayerPath? – Koh

+0

因爲你需要掩蓋內部矩形周圍的一切,而不是矩形本身。您可以添加此行以查看mask的工作方式let superlayerPath = UIBezierPath.init(ovalIn:blurView.frame) –

+0

非常感謝ans.Now我想在該區域添加陰影。如何可以。請幫助我。 @VitalyMigunov –