Objective c 如何在OSX中在CALayer上绘制字符串?

Objective c 如何在OSX中在CALayer上绘制字符串?,objective-c,macos,calayer,Objective C,Macos,Calayer,我在自定义CALayer中绘制字符串时遇到问题。调用了drawInContext方法,但在屏幕上看不到任何内容。我可以用纯色填充图层,但似乎无法在上面画线 有什么建议吗?谢谢 - (void)drawInContext:(CGContextRef)ctx { CGContextSaveGState(ctx); NSString *myString = @"Hello World"; NSDictionary *attr = [NSDictionary dicti

我在自定义CALayer中绘制字符串时遇到问题。调用了drawInContext方法,但在屏幕上看不到任何内容。我可以用纯色填充图层,但似乎无法在上面画线

有什么建议吗?谢谢

- (void)drawInContext:(CGContextRef)ctx
{
    CGContextSaveGState(ctx);

    NSString *myString = @"Hello World";    
    NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSFont systemFontOfSize:14], NSFontAttributeName, nil];

    [myString drawAtPoint:NSMakePoint(0,0) withAttributes:attr];

    CGContextRestoreGState(ctx);
}

您可能需要使用CATextLayer。获取父层,将文本添加到TextLayer,然后使用-addSublayer将TextLayer添加到父层

我不想用石英来画线,但我想我必须这样做。这就是我最后要做的

   NSString *string = @"Hello world";
   CGContextSelectFont (ctx,"Helvetica", 24, kCGEncodingMacRoman);
   CGContextSetTextDrawingMode (ctx, kCGTextFillStroke);
   CGContextShowTextAtPoint (ctx, 40, 40, [string UTF8String], (int)[string length]);
替代解决方案

    [NSGraphicsContext saveGraphicsState];

    NSGraphicsContext *currentContext = [NSGraphicsContext graphicsContextWithGraphicsPort:theContext flipped:NO];
    [NSGraphicsContext setCurrentContext:currentContext]; 

    //Draw here

    [NSGraphicsContext restoreGraphicsState];

我有我需要绘制的各种属性的文本。我宁愿自己绘制文本,因为它比为所有字符串创建CATextLayer并放入父层更通用。