把文字转换成图片

2019-01-10  本文已影响5人  化二缺
- (UIImage *)imageWithString:(NSString *)string font:(UIFont *)font color:(UIColor *)color
{
    CGSize size = [string sizeWithFont:font constrainedToSize:CGSizeMake(CGFLOAT_MAX, 30) lineBreakMode:NSLineBreakByWordWrapping];
    NSDictionary *attributes = @{NSFontAttributeName : font,
                                 NSForegroundColorAttributeName : color};
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:string attributes:attributes];

    UIGraphicsBeginImageContextWithOptions(size, 0, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetCharacterSpacing(ctx, 10);

    CGContextSetTextDrawingMode(ctx, kCGTextFill);

    CGContextSetRGBFillColor(ctx, 255, 255, 255, 1);

    [attributedString drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}
上一篇下一篇

猜你喜欢

热点阅读