views:

565

answers:

2

I have an NSString that I would like to draw it's contents to a UIImage but have absolutely NO idea how I would go about doing this. I need to call a method that I give it an NSString and returns a UIImage with the text drawn into it.

Please help!!

+2  A: 

Begin an image context with UIGraphicsBeginImageContext, draw to it, get an image with UIGraphicsGetImageFromCurrentImageContext, end it with UIGraphicsEndImageContext

Graham Lee
How do I draw the NSString to it? That was what I was asking. PLEASE!
Jaba
look at NSString UIKit Additions - there're multiple nsstring drawing functions available - like 'drawAtPoint:withFont:' or 'drawInRect:withFont:' and others
Vladimir
@Jaba: look at `CGContextShowTextAtPoint` and related functions.
Graham Lee
Thank you so much I will research that.
Jaba
+6  A: 

You can try this: (updated for iOS 4)

-(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 grayColor] CGColor]);

    // draw in context, you can use also drawInRect:withFont:
    [text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];

    // transfer image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    return image;
}

To call it:

UIImage *image = [self imageFromText:@"This is a text"];
for iOS4+ you should create the context with scaling 0.0 as to get the main screen's scaling if the scaling is not 1.0 (retina display is 2.0): UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
valexa