Search code examples
iphoneuiimagensstringword-wrap

iPhone: Create image from NSString with word wrap


I am using following function for converting an NSString to an image.

-(UIImage *)imageFromText:(NSString *)text FontName:(UIFont *)font
{
    // set the font type and size
    //UIFont *font = [UIFont systemFontOfSize:20.0];  
    CGSize size  = [text sizeWithFont:font];

    UIGraphicsBeginImageContext(size);

    [text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];

    // transfer image
    CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), YES);
    CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);

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

    return image;
}

It works well. The problem is that when the string contains long text, then it creates an image for which the width is too much. I want to apply a word wrap functionality if the text beyond the range.

So how can I create a image with word wrap of NSString?


Solution

  • You need to call drawInRect:withAttributes: method on NSString.