How do I use the NSString draw functionality to create a UIImage from text

后端 未结 4 1513
说谎
说谎 2020-11-28 02:59

I would like to draw the content of a NSString variable in a UIImage, but I have absolutely no idea how to do this. I need to write a method that w

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 04:03

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

提交回复
热议问题