我尝试在文本上绘制一个三角形,并在与文本相交的位置绘制形状。
当我尝试应用蒙版时,文字就会消失。 这是代码:
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)
}
}
答案 0 :(得分:0)
所以我想出了如何做到这一点。但它对我来说感觉不对。必须有更好的方法来实现它。
我添加了UIView并将其放入文本中,然后将蒙版应用于视图。它奏效了。但为什么它首先不起作用。
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
}
}