Simply mask a UIView with a rectangle

前端 未结 7 1466
别跟我提以往
别跟我提以往 2020-11-30 20:10

I want to know how to simply mask the visible area of a UIView of any kind. All the answers/tutorials I\'ve read so far describe masking with an image, gradient or creating

相关标签:
7条回答
  • 2020-11-30 20:41

    Very simple example in a Swift ViewController, based on the accepted answer:

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let redView = UIView(frame: view.bounds)
            view.addSubview(redView)
    
            view.backgroundColor = UIColor.green
            redView.backgroundColor = UIColor.red
    
            mask(redView, maskRect: CGRect(x: 50, y: 50, width: 50, height: 50))
        }
    
        func mask(_ viewToMask: UIView, maskRect: CGRect) {
            let maskLayer = CAShapeLayer()
            let path = CGPath(rect: maskRect, transform: nil)
            maskLayer.path = path
    
            // Set the mask of the view.
            viewToMask.layer.mask = maskLayer
        }
    }
    

    Output

    0 讨论(0)
提交回复
热议问题