Thursday, September 11, 2014

Convert NSString to UIImage

-(UIImage *)imageFromText:(NSString *)text
{
    // set the font type and size
    UIFont *font = [UIFont systemFontOfSize:20.0];
    CGSize size  = [text sizeWithFont:font];
    
    // check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
    if (UIGraphicsBeginImageContextWithOptions != NULL)
        UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
    else
        // iOS is < 4.0
        UIGraphicsBeginImageContext(size);
    
    // optional: add a shadow, to avoid clipping the shadow you should make the context size bigger
    //
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetShadowWithColor(ctx, CGSizeMake(1.0, 1.0), 5.0, [[UIColor brownColor] CGColor]);
    
    // draw in context, you can use also drawInRect:withFont:
    [text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
    
    //CGImageRef cimg = UIGraphicsGetCurrentContext();
    
    // transfer image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    [image drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
    
    //CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(ctx, 2.0, 3.5, 5.0, 1.0);
    CGContextStrokeRect(ctx, rect);
    UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();    
    
    return testImg;

}

No comments:

Post a Comment