CAShapeLayer : Identify shape : Add CATextLayer in that shape

223 views Asked by At

I have SVG file and i was able to access SVG's shapes using SVGKit.

Now, I have CAShapeLayer which may contain circle, square or any closed shape.

I want to add CATextLayer on CAShapeLayer in such way that text should not cross the defined shape.

Here is the example of crossing CATextLayer on CAShapeLayer :

enter image description here enter image description here

It's crossing just because, CATextLayer is starting from 0 position of CAShapeLayer which contains circle in particular this case.

In my case, CAShapeLayer can contain any closed shape. It can be oval also.

How can I identify shape inside CAShapeLayer? or How can I apply path to CATextLayer? which will makes sure text will be drawn inside shape?

Here is code to add CATextLayer On CAShapeLayer:

-(CATextLayer *)addTrackerNumberToLayer:(NSString *)numbers{
    self.numbersTextLayer = [CATextLayer new];
    self.numbersTextLayer.foregroundColor = [UIColor blackColor].CGColor;
    self.numbersTextLayer.font = (__bridge CFTypeRef _Nullable)([UIFont boldSystemFontOfSize:15]);
    self.numbersTextLayer.fontSize=25;
    self.numbersTextLayer.anchorPoint = CGPointZero;
    self.numbersTextLayer.frame = CGRectMake(self.parentShapeLayer.bounds.size.width*0.05, self.parentShapeLayer.bounds.size.height*0.05, self.parentShapeLayer.bounds.size.width*0.90, self.parentShapeLayer.bounds.size.height*0.30);
    self.numbersTextLayer.position = CGPointMake(self.parentShapeLayer.bounds.size.width*0.05,self.parentShapeLayer.bounds.size.height*0.05);
    self.numbersTextLayer.alignmentMode = kCAAlignmentCenter;

    [self.parentShapeLayer addSublayer:self.numbersTextLayer];
}
1

There are 1 answers

1
Syed Qamar Abbas On

Use isWrapped property of CATextLayer this determines whether the text is wrapped to fit within the receiver’s bounds.

-(CATextLayer *)addTrackerNumberToLayer:(NSString *)numbers{
    self.numbersTextLayer = [CATextLayer new];
    self.numbersTextLayer.foregroundColor = [UIColor blackColor].CGColor;
    self.numbersTextLayer.font = (__bridge CFTypeRef _Nullable)([UIFont boldSystemFontOfSize:15]);
    self.numbersTextLayer.fontSize=25;
    self.numbersTextLayer.anchorPoint = CGPointZero;
    self.numbersTextLayer.frame = CGRectMake(self.parentShapeLayer.bounds.size.width*0.05, self.parentShapeLayer.bounds.size.height*0.05, self.parentShapeLayer.bounds.size.width*0.90, self.parentShapeLayer.bounds.size.height*0.30);
    self.numbersTextLayer.position = CGPointMake(self.parentShapeLayer.bounds.size.width*0.05,self.parentShapeLayer.bounds.size.height*0.05);
    self.numbersTextLayer.alignmentMode = kCAAlignmentCenter;
    [self.numbersTextLayer setWrapped:YES];//User Wrapped to YES to imbound the text to fit in the region.
    [self.parentShapeLayer setMasksToBounds:YES];
    [self.parentShapeLayer addSublayer:self.numbersTextLayer];
    return self.numbersTextLayer;
}