在UIBezierPath中写入文本

时间:2015-12-02 00:49:16

标签: ios objective-c

我试图做一些非常简单的事情,但我不知道如何用obj c做。我想写字符串" hello world"在我的UIBezierPath用作形状的CAShapeLayer中。你能告诉我代码是怎么做的吗?我只想在形状

中写这个字符串

我在下面有这个UIBezierPath:
 UIBezierPath* oval2Path = [UIBezierPath bezierPathWithOvalInRect: oval2Rect];

在我的viewcontroller中,不知道如何在其中添加文本

3 个答案:

答案 0 :(得分:0)

为什么不在UIView的子类中执行此操作?你可以这样做:

-(void)drawRect{
    UIBezierPath* oval2Path = [UIBezierPath bezierPathWithOvalInRect: self.bounds];
    [oval2Path addClip];
    [@"Hello World" drawInRect:self.bounds withAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:self.bounds.size.height]}];
}

答案 1 :(得分:0)

我发现了一些使用Core Text执行此操作的教程(12),但是从iOS 7开始,您可以使用UITextView和TextKit来执行此操作:

UIBezierPath *exclusionPath = ...; // some bezier path
textView.textContainer.exclusionPaths = @[exclusionPath];

(TextKit解决方案来自this tutorial。)

答案 2 :(得分:0)

我在这里使用bezier路径和文本创建一些圆圈

for (int i = 0; i < numberOfArcs.count; i++) {
    NSInteger startAngele   =   i * 360/numberOfArcs.count+270;
    NSInteger endAngele;
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];

        [bezierPath addArcWithCenter:CGPointMake(self.bounds.size.width/2.0, self.bounds.size.width/2.0) radius:0.25  * self.bounds.size.width startAngle:degreesToRadians(startAngele) endAngle:degreesToRadians(endAngele) clockwise:YES];
    }

使用CAShapelayer在bezier路径上写文本,CATextlayer使用此代码

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