How can I highlight the font of the text?

I would like to display text with a different color in it (outline). I am trying to display text in a MapOverlayView using

[text drawAtPoint:CGPointMake(0,30) withFont:[UIFont fontWithName:@"Helvetica-Bold" size:(3 * MKRoadWidthAtZoomScale(zoomScale))] 

It works fine, except that I need text to display the outlines.

+6
source share
2 answers

Yes, you can display the selected text using CGContextSetDrawingMode(CGContextRef, CGTextDrawingMode) , although you probably need to adjust some numbers and colors to make them look good.

It seems logical to use kCGTextFillStroke, but this can lead to a stroke that suppresses filling. If you stroke and then fill, as in the block below, you will get a visible outline behind the text to be read.

 CGContextRef context = UIGraphicsGetCurrentContext(); CGPoint point = CGPointMake(0,30); CGFloat fontSize = (3 * MKRoadWidthAtZoomScale(zoomScale)); UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:fontSize]; // Draw outlined text. CGContextSetTextDrawingMode(context, kCGTextStroke); // Make the thickness of the outline a function of the font size in use. CGContextSetLineWidth(context, fontSize/18); CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]); [text drawAtPoint:point withFont:font]; // Draw filled text. This will make sure it clearly readable, while leaving some outline behind it. CGContextSetTextDrawingMode(context, kCGTextFill); CGContextSetFillColorWithColor(context, [[UIColor blueColor] CGColor]); [text drawAtPoint:point withFont:font]; 
+8
source

The accepted answer did not work for me because drawAtPoint:withFont: deprecated. I managed to get it to work with the following code:

 CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat fontSize = 18.0; CGPoint point = CGPointMake(0, 0); UIFont *font = [UIFont fontWithName:@"Arial-BoldMT" size:fontSize]; UIColor *outline = [UIColor whiteColor]; UIColor *fill = [UIColor blackColor]; NSDictionary *labelAttr = @{NSForegroundColorAttributeName:outline, NSFontAttributeName:font}; CGContextSetTextDrawingMode(context, kCGTextStroke); CGContextSetLineWidth(context, 2.0); [text drawAtPoint:point withAttributes:labelAttr]; CGContextSetTextDrawingMode(context, kCGTextFill); CGContextSetLineWidth(context, 2.0); labelAttr = @{NSForegroundColorAttributeName:fill, NSFontAttributeName:font}; [text drawAtPoint:point withAttributes:labelAttr]; 
0
source

Source: https://habr.com/ru/post/912542/


All Articles