开发者

iPhone - Draw white text on black view using CGContext

开发者 https://www.devze.com 2023-04-01 21:44 出处:网络
I can\'t achieve drawing som开发者_C百科e white text on a black view using CGContext in a drawRect method.

I can't achieve drawing som开发者_C百科e 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 ?


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.


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];


On shorter example try using [[UIColor whiteColor] set] before the drawAtPoint: call.


Works with :

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

But still need some transformations to be displayed not mirrored :-)


This will work with this code :

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号