iOS, Draw text with stroke on UIImage

caoimghgin picture caoimghgin · Feb 9, 2013 · Viewed 11k times · Source

I am currently drawing text onto a UIImage which appears in an AnnotationView in an iOS Map - custom icons which appear at certain long/lat coordinates. Works well. However, I would like to draw this text with a white stroke (you might call it an outline).

// Draw text and add to a UIImage iOS 5/6

+ (UIImage*)drawText:(NSString*)string inImage:(UIImage*)image atPoint:(CGPoint)point {

    UIFont *font = [UIFont boldSystemFontOfSize:12];
    UIGraphicsBeginImageContext(image.size);
    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];

    CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
    [[UIColor whiteColor] set];
    [string drawInRect:CGRectIntegral(rect) withFont:font];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;

}

Answer

MobileVet picture MobileVet · Oct 25, 2013

NSAttributedString is definitely the way to go, especially if you want it to work in iOS7. For your example, you can just replace the two text blocks with the following:

// draw stroke
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:font forKey:NSFontAttributeName];
[attributes setObject:[NSNumber numberWithFloat:4] forKey:NSStrokeWidthAttributeName];
[attributes setObject:[UIColor whiteColor] forKey:NSStrokeColorAttributeName];
[self.text drawInRect:rect withAttributes:attributes];

// draw fill
[attributes removeObjectForKey:NSStrokeWidthAttributeName];
[attributes removeObjectForKey:NSStrokeColorAttributeName];
[attributes setObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName];
[self.text drawInRect:rect withAttributes:attributes];