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

时间:2016-01-27 12:45:10

标签: ios swift calayer core-text cashapelayer

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

enter image description here

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

现在我需要在这个圈子的中间添加一个文本,我试图在谷歌上找到它,但没有任何工作正常。我不确定是否可能,如果有可能,有人可以帮助我吗?

4 个答案:

答案 0 :(得分:5)

我想你应该将CATextLayer添加为CALayer的子图层......这样做很好:首先尝试添加CAShapeLayer,然后CATextLayer添加CALayer // assume self - is UIView instance self.layer.addSublayer(shapedLayer) // shapedLayer - CAShapeLayer instance self.layer.addSublayer(textLayer) // textLayer - CATextLayer instance 父图层),例如按以下顺序...

Any

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

CAShapeLayer上的文字使用CATextLayer

这里我创建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];
        }

答案 3 :(得分:0)

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

labelFrame -CGRect

someString -字符串

图层-您的图层

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