确定CATextLayer中textBox的大小

时间:2016-10-17 17:01:18

标签: ios swift graphics calayer catextlayer

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

1 个答案:

答案 0 :(得分:9)

是的,雅虎!

这就是答案!

myTextLayer.preferredFrameSize()