Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out the size of the textBox in a CATextLayer

I wrote this code, works well; but I need to figure out the size of the text in the CATextLayer to finish it? The idea I use from a tap gesture to get the x/y, enter the text and have it figure out the CGSize needed to draw it in the CATextLayer object/view.

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)
}
like image 930
user3069232 Avatar asked Dec 25 '22 00:12

user3069232


1 Answers

Yes, Yahoo!

This is the answer!

myTextLayer.preferredFrameSize()
like image 162
user3069232 Avatar answered Jan 18 '23 17:01

user3069232