将文本添加到CALayer

chr*_*o16 29 iphone

是否可以在没有子类化UILabelCALayer情况下添加a 并将其绘制成drawInContext:

谢谢!

小智 148

CATextLayer *label = [[CATextLayer alloc] init];
[label setFont:@"Helvetica-Bold"];
[label setFontSize:20];  
[label setFrame:validFrame];
[label setString:@"Hello"];
[label setAlignmentMode:kCAAlignmentCenter];
[label setForegroundColor:[[UIColor whiteColor] CGColor]];
[layer addSublayer:label];

[label release];
Run Code Online (Sandbox Code Playgroud)

  • 您需要调整CALayer的内容比例,否则您将在视网膜(@ 2x)或@ 3x设备上获得模糊文本.使用:label.contentsScale = [UIScreen mainScreen] .scale; (17认同)
  • 恕我直言,这是一个比自定义CALayer或图层委托更简单的解决方案,只要您不需要超过基本文本绘图.CATextLayer已经知道如何绘制文本,因此无需重新发明轮子. (4认同)
  • @bicycle,来吧,如果不是Stack Overflow,我们都没有工作 (4认同)

Dee*_*olu 38

我不认为你可以将一个UIView子类添加到CALayer对象.但是,如果要在CALayer对象上绘制文本,可以使用NSString UIKit 添加中提供的绘图功能来完成,如下所示.虽然我的代码是在委托的drawLayer:inContext方法中完成的,但同样可以在子类'drawInContext:方法中使用.您是否想要利用任何特定的UILabel功能?

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
  CGContextSetFillColorWithColor(ctx, [[UIColor darkTextColor] CGColor]);

  UIGraphicsPushContext(ctx);
  /*[word drawInRect:layer.bounds 
          withFont:[UIFont systemFontOfSize:32] 
     lineBreakMode:UILineBreakModeWordWrap 
         alignment:UITextAlignmentCenter];*/

  [word drawAtPoint:CGPointMake(30.0f, 30.0f) 
           forWidth:200.0f 
           withFont:[UIFont boldSystemFontOfSize:32] 
      lineBreakMode:UILineBreakModeClip];

  UIGraphicsPopContext();
}
Run Code Online (Sandbox Code Playgroud)


Fai*_*ash 6

只是为了记录我的方法,我在 Swift 4+ 中这样做了:

let textlayer = CATextLayer()

textlayer.frame = CGRect(x: 20, y: 20, width: 200, height: 18)
textlayer.fontSize = 12
textlayer.alignmentMode = .center
textlayer.string = stringValue
textlayer.isWrapped = true
textlayer.truncationMode = .end
textlayer.backgroundColor = UIColor.white.cgColor
textlayer.foregroundColor = UIColor.black.cgColor

caLayer.addSublayer(textlayer) // caLayer is and instance of parent CALayer 
Run Code Online (Sandbox Code Playgroud)


Bra*_*son 5

您的 UILabel 背后已经有一个 CALayer。如果您将多个 CALayer 放在一起,则可以将 UILabel 的图层添加为其中一个的子图层(通过使用其layer属性)。

如果是在您想要的图层中直接绘制文本,Deepak 指向的 UIKit NSString 添加是要走的路。例如,Core Plot 框架有一个独立于 Mac/iPhone 平台的 CALayer 子类,它执行文本渲染,CPTextLayer