确定CATextLayer中textBox的大小

use*_*232 4 graphics calayer ios catextlayer swift

我写了这段代码,效果很好; 但我需要弄清楚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)
}
Run Code Online (Sandbox Code Playgroud)

use*_*232 9

是的,雅虎!

这就是答案!

myTextLayer.preferredFrameSize()
Run Code Online (Sandbox Code Playgroud)