How could I outline Text font?

后端 未结 2 1116
你的背包
你的背包 2021-02-06 11:04

I would like to display text with another color in it\'s border (outline). i\'m trying to display a text in MapOverlayView using

[text drawAtPoint:CGPointMake(0         


        
相关标签:
2条回答
  • 2021-02-06 11:19

    Yes, you can display outlined text with the aid of CGContextSetDrawingMode(CGContextRef, CGTextDrawingMode), although you'll probably need to adjust some numbers and colors to make it look good.

    It make seem logical to use kCGTextFillStroke, but that can make the stroke overwhelm the fill. If you stroke, then fill, as in the block below, you get a visible outline behind readable text.

    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's clearly readable, while leaving some outline behind it.
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextSetFillColorWithColor(context, [[UIColor blueColor] CGColor]);
    [text drawAtPoint:point withFont:font];
    
    0 讨论(0)
  • 2021-02-06 11:25

    The accepted answer didn't work for me possibly because drawAtPoint:withFont: is deprecated. I was able 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 讨论(0)
提交回复
热议问题