如何在 CAShapeLayer 中添加标签或文本

How to add label or text in to CAShapeLayer

这是我的class,它会画一个圆,看起来像这样:

    class OvalLayer: CAShapeLayer {

    let animationDuration: CFTimeInterval = 0.3

    override init() {
        super.init()
        fillColor = Colors.green.CGColor
        path = ovalPathSmall.CGPath
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    var ovalPathStart: UIBezierPath {
        let path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))

        return path
    }
}

现在我需要在这个圆圈的中间添加一个文本,我试图在 google 上找到它,但没有任何效果。我不确定是否可行,如果可行,谁能帮助我?

我想你应该将 CATextLayer 作为子层添加到 CALayer... 这样工作很好:尝试先添加 CAShapeLayer,然后再添加 CATextLayer(到相同的 CALayer 父层),例如按以下顺序...

// assume self - is UIView instance

self.layer.addSublayer(shapedLayer) // shapedLayer - CAShapeLayer instance
self.layer.addSublayer(textLayer) // textLayer - CATextLayer instance

您只需要获取 UIBezierPath 的中心,然后向当前图层添加标签或 CATextLayer

let center : CGPoint = CGPoint(x: CGRectGetMidX(ovalPathStart.bounds), y: CGRectGetMidX(ovalPathStart.bounds))

现在,创建一个 UILabelCATextLayer 并设置中心。

Swift 3.0

let label = UILabel()
label.font = UIFont(name: "Helvetica-Bold", size: 12)
label.frame = CGRect(x: OvalLayer.frame.origin.x + (circleWidth/2), y: OvalLayer.frame.origin.y, width: OvalLayer.bounds.width, height: OvalLayer.bounds.height)
label.text = "Hello"
label.textColor = UIColor.red
label.isHidden = false

OvalLayer.addSublayer(label.layer)

使用 CATextLayer 在 CAShapeLayer 上添加文字

这里我正在创建 CAShapeLayer 对象,我正在将 CATextLayer 添加到 CAShapeLayer 这里 numberOfArcsCount 表示一些 8

            CAShapeLayer *progressLayer = [[CAShapeLayer alloc] init];
            [progressLayer setPath:bezierPath.CGPath];


            CATextLayer* text = [CATextLayer new];
            for (int i = 1; i <= numberOfArcs.count; i++) {
            text.string =  [NSString stringWithFormat:@"%i", i];
            text.font = (__bridge CFTypeRef _Nullable)([UIFont fontWithName:@"akaChen" size:42]);
            text.font = (__bridge CFTypeRef _Nullable)([UIFont boldSystemFontOfSize:15]);
            text.fontSize=25;
            text.frame = CGRectMake(0,0,40,40);
            text.position = CGPointMake(CGRectGetMidX(progressLayer.frame) ,CGRectGetMidY(progressLayer.frame) );

            CGFloat vert = CGRectGetMidY(progressLayer.frame) / CGRectGetHeight(text.frame);

            text.anchorPoint = CGPointMake(0.5, vert );
            text.alignmentMode = kCAAlignmentCenter;
            text.foregroundColor = [[UIColor whiteColor] CGColor];

           [progressLayer addSublayer:text];
        }

这种给图层添加标签的方法:

labelFrame - CGRect

someString - 字符串

图层 - 你的图层

        let label = CATextLayer()
        label.frame = labelFarme
        label.string = someString
        layer.addSublayer(label)