CAShapeLayer:识别形状:在该形状中添加CATextLayer

时间:2018-02-27 10:47:31

标签: ios objective-c cashapelayer svgkit

我有 SVG 文件,我可以使用SVGKit访问SVG的形状。

现在,我有CAShapeLayer可能包含圆形,方形或任何封闭形状。

我想在CATextLayer上添加CAShapeLayer,使文字不会超出定义的形状。

以下是在CATextLayer上交叉CAShapeLayer的示例:

enter image description here enter image description here

它只是因为,CATextLayerCAShapeLayer的0位开始,其中包含圆圈,特别是这种情况。

就我而言,CAShapeLayer可以包含任何封闭的形状。它也可以是椭圆形的。

如何识别CAShapeLayer内的形状?或者我如何应用CATextLayer的路径?这将确保文本将在形状内绘制?

以下是在CATextLayer上添加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 个答案:

答案 0 :(得分:0)

使用isWrapped CATextLayer属性确定文本是否被包装以适合接收者的范围。

-(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;
}