在UIBezierPath中写入文本

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

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

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

你为什么不在UIView的子类中这样做? 你可以这样做:

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

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

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

(TextKit解决方案来自本教程 。)

在这里,我也使用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在贝塞尔路径上编写文本,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]; }