iPhone - Draw white text on black view using CGContext
Solution 1
Works with :
CGContextShowTextAtPoint (context, center.x, center.y, "Some text", strlen("Some text"));
But still need some transformations to be displayed not mirrored :-)
Solution 2
Ok after a couple of hours and reading the Quartz 2D programming guide I discovered that you also have to set the FILL color, not just the STROKE color. So the follow code works.
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
I needed to show chart labels on a darkGray border. Now the labels appear in white.
Solution 3
This will draw a string in white in a black rectangle
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];
Solution 4
On shorter example try using [[UIColor whiteColor] set]
before the drawAtPoint:
call.
Oliver
Updated on June 05, 2022Comments
-
Oliver almost 2 years
I can't achieve drawing some white text on a black view using CGContext in a drawRect method.
I do :
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;
And then...
Impossible to find the correct method.
I've tried this :UIFont* font = [UIFont fontWithName:@"Geneva" size:12.0]; [@"Some text" drawAtPoint:center withFont:font];
But it does not work.
I don't find any CGContext method for that. Where is it hidden ?
How may I draw that text in white ?
-
Marcelo Alves over 12 yearsare you sure your drawRect: is being called? Just tried here with a small sample and it works flawlessly.
-
amattn over 12 yearsBe careful. Last I checked, this only works for ASCII, not Unicode.
-
Oliver over 12 yearsOK, but that didn't work. The method I give in my found solution solved the preblem (but text is mirrored).
-
fishinear about 11 yearsActually, you only need to set the fill color, the stroke color is not used by text
-
Todd Lehman about 8 yearsNote that you can also write
UIColor.whiteColor.CGColor
in Objective-C 2.0 dot syntax. -
Ky - over 6 years
'CGContextShowTextAtPoint' is unavailable: APIs deprecated as of OS X 10.9 and earlier are unavailable in Swift