0

I am trying to make a CAShapeLayer

with a sublayer of CATextLayer to follow a UIBezierPath.

I am able to draw the CAShapeLayer using UIBezierPath but CATextLayer doesn't follow the same path. Here is what I did so far.

        // Define a bezier path

        let bezierPath = UIBezierPath.init()
        let origin = CGPoint.init(x: containerView.frame.size.width-75, y: 0)
        let firstPoint  = CGPoint.init(x: origin.x+34, y: origin.y)
        let secondPoint = CGPoint.init(x: containerView.frame.size.width, y: origin.y+25)
        let thirdPoint  = CGPoint.init(x: secondPoint.x, y: secondPoint.y+25)
        bezierPath.move(to: origin)
        bezierPath.addLine(to: firstPoint)
        bezierPath.addLine(to: secondPoint)
        bezierPath.addLine(to: thirdPoint)
        bezierPath.addLine(to: origin)
        bezierPath.close()

        // Add a shape to follow the defined Bezier Path

        let shape = CAShapeLayer.init()
        shape.path  = bezierPath.cgPath
        shape.fillColor = UIColor.yellow.cgColor
        containerView.layer.addSublayer(shape)

        // Add a text layer

        let textlayer = CATextLayer.init()
        textlayer.string = "iPhone X"
        textlayer.fontSize = 12
        textlayer.frame = bezierPath.bounds
        shape.addSublayer(textlayer)

This is what I got as result, the text should follow the same path

Rohit Kumar
  • 877
  • 6
  • 20
  • If all you need is a rotation, you should consider an affine transform. – ZhangChn Jan 10 '18 at 05:54
  • That's the only thing I can also think of right now but I am looking for something if we can just make it follow the same path as the text layer was added to the same path. – Rohit Kumar Jan 10 '18 at 05:56
  • You need to create a layer class for that, which uses CoreText for drawing the text. There is an [example](https://developer.apple.com/library/content/samplecode/CoreTextArcCocoa/Introduction/Intro.html) from Apple for that. Unfortunately, it's Objective-C. – clemens Jan 10 '18 at 06:17
  • Clemens, I wish I could understand this example but seems like it's way beyond me. – Rohit Kumar Jan 10 '18 at 06:46
  • @RohitKumar i think it's better to go with affine transform as ZhangChn said or else you can use this library https://github.com/mukeshthawani/TriLabelView. – Shezad Jan 10 '18 at 06:53
  • Shehzad, though it's a little different but I can use it. Thanks a lot for the reference. – Rohit Kumar Jan 10 '18 at 09:36

0 Answers0