iOS,在 UIImage 上绘制带笔划的文本

标签 ios objective-c fonts uiimage stroke

我目前正在将文本绘制到 UIImage 上,该 UIImage 出现在 iOS map 的 AnnotationView 中 - 出现在某些长/纬度坐标处的自定义图标。效果很好。但是,我想用白色笔划(您可以称之为轮廓)绘制此文本。

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

}

最佳答案

NSAttributedString 绝对是最佳选择,特别是如果你想让它在 iOS7 中工作。对于您的示例,您可以将两个文本 block 替换为以下内容:

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

关于iOS,在 UIImage 上绘制带笔划的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14783771/

相关文章:

java - 如何在 java 中从 jar 加载嵌入字体作为 InputStream?

java - 是否有与 FontUtilities.getCompositeFontUIResource(Font) 等效的非专有等效项?

ios - 设备休眠时的 Alamofire 请求

ios - 无法将 View 放在导航栏上方

iOS TableView(错误 : two scroll Bars Found As Zoomed)

ios - Objective-C:从可空指针 'NSURL * _Nullable' 到不可空指针类型 'NSURL * _Nonnull'

iphone - 自定义字体显示不正确?

ios - 如何在iOS 13模拟器中使用深色模式?

objective-c - 如何以编程方式用 CoreData 行填充 NSArrayController?

ios - 两个 NSNumber 数组的 NSPredicate