iOS UIView subclass, draw see-through text to background

后端 未结 4 1830
灰色年华
灰色年华 2020-12-01 08:51

I want to draw text onto my subclass on UIView so that the text is cut out of the shape and the background behind the view shows through, just like in the OSX Mavericks logo

4条回答
  •  天涯浪人
    2020-12-01 09:12

    StatusReport's accepted answer is beautifully written and because I have yet to find a Swift answer to this question, I thought I'd use his answer as the template for the Swift version. I added a little extensibility to the view by allowing the input of the string as a parameter of the view to remind people that that his can be done with all of the view's properties (corner radius, color, etc.) to make the view completely extensible.

    The frame is zeroed out in the initializer because you're most likely going to apply constraints. If you aren't using constraints, omit this.

    Swift 5

    class CustomView: UIView {
        var title: String
        
        init(title: String) {
            self.title = title
            super.init(frame: CGRect.zero)
            config()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func config() {
            backgroundColor = UIColor.clear
        }
        
        override func draw(_ rect: CGRect) { // do not call super
            UIColor.red.setFill()
            let path = UIBezierPath(roundedRect: bounds, cornerRadius: 10)
            path.fill()
            weak var context = UIGraphicsGetCurrentContext() // Apple wants this to be weak
            context?.saveGState()
            context?.setBlendMode(CGBlendMode.destinationOut)
            title.draw(at: CGPoint.zero, withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 24)])
            context?.restoreGState()
        }
    }
    
    let customView = CustomView(title: "great success")
    

提交回复
热议问题