我有一个 CALayer,我首先在上面画了一些东西,然后是一个文本:
- (void)drawInContext:(CGContextRef)context
{
CGContextSaveGState(context);
// draw things, everything displays correctly ...
CGSize expectedCreditSize = [[gpData.credits stringValue] sizeWithFont:[UIFont
systemFontOfSize:self.fontSize]];
rect = CGRectMake(self.bounds.origin.x, self.bounds.size.height/2,
expectedCreditSize.width, expectedCreditSize.height);
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
[self.creditString drawInRect:rect
withFont:[UIFont systemFontOfSize:self.fontSize]
lineBreakMode:NSLineBreakByWordWrapping
alignment:NSTextAlignmentRight];
CGContextRestoreGState(context);
}
所有图形内容都正确显示,但文本根本不正确。我究竟做错了什么?
我还尝试将 CATextLayer 添加为 subLayer,但因此在运行时收到错误消息。
CATextLayer *creditsTextLayer = [[CATextLayer alloc] init];
[creditsTextLayer setFrame:self.frame];
[creditsTextLayer setPosition:self.position];
[creditsTextLayer setString:self.creditString];
[creditsTextLayer setFontSize:self.fontSize];
[creditsTextLayer setAlignmentMode:kCAAlignmentLeft];
[creditsTextLayer setForegroundColor:[[UIColor whiteColor] CGColor]];
[self addSublayer:creditsTextLayer];
唯一有效的是这个解决方案:
CGContextSelectFont (context,
"Helvetica-Bold",
self.fontSize,
kCGEncodingMacRoman);
CGContextSetTextDrawingMode (context, kCGTextFill);
CGContextSetRGBFillColor (context, 0, 1, 0, .5);
CGContextSetRGBStrokeColor (context, 0, 0, 1, 1);
CGContextShowTextAtPoint (context, 40, 0, self.creditString, 9);
但这很不舒服。
有没有人知道,我能做些什么来提出我的第一个工作建议?我错过了显示文本的东西吗?
提前致谢!
编辑:
基于Seamus的回答,我现在开始工作了
- (void)drawInContext:(CGContextRef)context
{
CGContextSaveGState(context);
// draw things like circles and lines,
// everything displays correctly ...
// now drawing the text
UIGraphicsPushContext(context);
CGSize expectedCreditSize = [[gpData.credits stringValue] sizeWithFont:[UIFont
systemFontOfSize:self.fontSize]];
rect = CGRectMake(self.bounds.origin.x, self.bounds.size.height/2,
expectedCreditSize.width, expectedCreditSize.height);
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
[self.creditString drawInRect:rect
withFont:[UIFont systemFontOfSize:self.fontSize]
lineBreakMode:NSLineBreakByWordWrapping
alignment:NSTextAlignmentRight];
UIGraphicsPopContext();
CGContextRestoreGState(context);
}
这意味着我只是推送和弹出文本的图形上下文。这有意义吗?为什么它适用于绘制其他 CGContext 东西?也许有人可以解释......</p>