Add text to CALayer

前端 未结 7 1991
Happy的楠姐
Happy的楠姐 2020-11-29 19:28

Is it possible to add a UILabel to a CALayer without subclassing and drawing it in drawInContext:?

Thanks!

7条回答
  •  温柔的废话
    2020-11-29 19:55

    I don't think you can add a UIView subclass to a CALayer object. However if you want to draw text on a CALayer object, it can be done using the drawing functions provided in NSString UIKit additions as shown below. While my code is done in the delegate's drawLayer:inContext method, the same can be used in subclass' drawInContext: method. Is there any specific UILabel functionality that you want to leverage?

    - (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();
    }
    

提交回复
热议问题