我写了这段代码,效果很好;但我需要弄清楚 CATextLayer 中文本的大小才能完成它?我从点击手势中使用的想法来获取 x/y,输入文本并让它找出在 CATextLayer 对象/视图中绘制它所需的 CGSize。
overload func ViewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
container.addGestureRecognizer(tap)
}
func handleTap(gesture: UITapGestureRecognizer) {
let location = gesture.location(in: gesture.view)
startX = location.x
startY = location.y
drawText(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:location.x, y:location.y))
}
func drawText(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) {
let myTextLayer = CATextLayer()
myTextLayer.string = "Google"
myTextLayer.backgroundColor = UIColor.black.cgColor
myTextLayer.foregroundColor = UIColor.white.cgColor
//myTextLayer.frame = view.bounds
let myBounds = CGRect(origin: start, size: CGSize(width: 128, height: 32))
myTextLayer.frame = myBounds
layer.addSublayer(myTextLayer)
}