iPhone-使用CGContext在黑色视图上绘制白色文本

iPhone-使用CGContext在黑色视图上绘制白色文本,iphone,cocoa-touch,text,colors,core-graphics,Iphone,Cocoa Touch,Text,Colors,Core Graphics,我无法在drawRect方法中使用CGContext在黑色视图上绘制一些白色文本 我有: CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor); CGCont

我无法在drawRect方法中使用CGContext在黑色视图上绘制一些白色文本

我有:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextSelectFont(context, "Helvetica", 20, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);

CGPoint center = self.center;
然后…
无法找到正确的方法。
我试过这个:

UIFont* font = [UIFont fontWithName:@"Geneva" size:12.0];
[@"Some text" drawAtPoint:center withFont:font];
但它不起作用

我找不到任何CGContext方法。它藏在哪里


如何以白色绘制该文本?

在较短的示例中,在调用
绘图点之前尝试使用
[[UIColor whiteColor]set]

可用于:

CGContextShowTextAtPoint (context, center.x, center.y, "Some text", strlen("Some text")); 

但是仍然需要一些转换来显示而不是镜像:-)

这将在黑色矩形中绘制一个白色字符串

NSString *text = @"Some text";
CGPoint center = CGPointMake(100, 200);
UIFont *font = [UIFont systemFontOfSize:14];

CGSize stringSize = [text sizeWithFont:font];
CGRect stringRect = CGRectMake(center.x-stringSize.width/2, center.y-stringSize.height/2, stringSize.width, stringSize.height);

[[UIColor blackColor] set];
CGContextFillRect(context, stringRect);

[[UIColor whiteColor] set];
[text drawInRect:stringRect withFont:font];

好的,几个小时后,阅读了Quartz 2D编程指南,我发现您还必须设置填充颜色,而不仅仅是笔划颜色。所以下面的代码是有效的

CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

我需要在黑色边框上显示图表标签。现在标签显示为白色。

这将适用于以下代码:

NSString *text = @"Some text";
UIFont *font = [UIFont systemFontOfSize:14];

[ text drawAtPoint:CGPointMake( 0, 0 ) withAttributes:@{ NSFontAttributeName:font, NSForegroundColorAttributeName : UIColor.redColor } ];

你确定你的drawRect:被调用了吗?在这里用一个小样品试用,效果完美。小心。上次我检查时,这只适用于ASCII,而不适用于Unicode。
'CGContextShowTextAtPoint'不可用:在OS X 10.9及更早版本中弃用的API在Swift中不可用
您的代码看起来基本正确。您不需要
CGContextSelectFont
CGContextSetTextDrawingMode
。还要再次检查中心值是否合理。好的,但这不起作用。我在找到的解决方案中给出的方法解决了这个问题(但文本是镜像的)。实际上,您只需要设置填充颜色,文本不使用笔划颜色。请注意,您还可以使用Objective-C 2.0点语法编写
UIColor.whiteColor.CGColor