我在自定义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);
}
答案 0 :(得分:2)
我不想使用Quartz来绘制字符串,但我想我必须这样做。所以这就是我最终做的事情
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];
答案 1 :(得分:0)
您可能想要使用CATextLayer。获取父图层,将文本添加到TextLayer,然后使用-addSublayer将TextLayer添加到父图层。