Hide text with a shape mask Swift

2019-09-10 02:51发布

问题:

I try to draw a triangle shape over the text, and to have the shape be painted where it intersects the text.

When I try to apply the mask, text just disappears. Here's the code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var messageLabel: UILabel!
    let maskLayer = CAShapeLayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        drawMask()
        messageLabel.layer.mask = maskLayer
    }

    func drawMask(){

        let path = UIBezierPath()

        let xMsgLbl = messageLabel.center.x-80
        let yMsgLbl = messageLabel.center.y-25

        path.moveToPoint(CGPointMake(xMsgLbl,yMsgLbl))
        path.addLineToPoint(CGPointMake(xMsgLbl+80, yMsgLbl+80))
        path.addLineToPoint(CGPointMake(xMsgLbl-80,yMsgLbl+80))
        path.addLineToPoint(CGPointMake(xMsgLbl,yMsgLbl))
        path.closePath()

        maskLayer.fillColor = UIColor.blueColor().CGColor
        maskLayer.path = path.CGPath

        view.layer.addSublayer(maskLayer)


    }
}

回答1:

So I figured out how to make this. But it just doesn't feel right to me. There has to be a better way to put it.

I've added UIView and put inside it my text, then applied mask to the view. And it worked. But why it didn't work at the first place.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView: UIView!
    @IBOutlet weak var messageLabel: UILabel!

    let maskLayer = CAShapeLayer()
    let path = UIBezierPath()

    override func viewDidLoad() {
        super.viewDidLoad()

        drawMask()

        maskLayer.opacity = 1.0
        view.layer.addSublayer(maskLayer)

        textView.layer.addSublayer(messageLabel.layer)
        messageLabel.layer.position.x = CGFloat(view.layer.position.x)+4

        messageLabel.layer.mask = maskLayer
        messageLabel.layer.masksToBounds = true

        textView.layer.mask = maskLayer
        textView.layer.masksToBounds = true

    }

    func drawMask(){

        let xMin = CGFloat(view.center.x)
        let yMin = CGFloat(view.center.y)-120

        path.moveToPoint(CGPointMake(xMin,yMin))
        path.addLineToPoint(CGPointMake(xMin+80, yMin+120))
        path.addLineToPoint(CGPointMake(xMin-80,yMin+120))
        path.addLineToPoint(CGPointMake(xMin,yMin))
        path.closePath()

        maskLayer.fillColor = UIColor.blackColor().CGColor
        maskLayer.path = path.CGPath

    }
}