iphone - 如何使用 NSString 绘制功能从文本创建 UIImage

标签 iphone nsstring uiimage

我想在UIImage中绘制NSString变量的内容,但我完全不知道如何做到这一点。我需要编写一个方法,该方法将接收 NSString 作为参数,并返回一个包含绘制到其中的文本的 UIImage

最佳答案

您可以尝试以下操作:(针对 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;
}

调用它:

UIImage *image = [self imageFromText:@"This is a text"];

关于iphone - 如何使用 NSString 绘制功能从文本创建 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2765537/

相关文章:

ios - 如何以编程方式创建包含内容的 UIImage

objective-c - 我们可以将 NSString 与 NSMutableString 进行比较吗

objective-c - 计算 NSString 中大写字母和数字的出现次数

ios - 从附加到电子邮件的文件名 PDF 的 NSString 中删除一些特殊字符

iOS 使用 vImage - 加速将 QCAR YUV 转换为 RGB

iphone - 定制非矩形按钮 三角形

iphone - 带动画的电子邮件图片

ios - resignFirstResponder 键盘不会在 segue 之前消失

iphone - 如何在 iPhonesdk 中创建 NSTimer

iphone - 如何检测 UIImage 中的 alpha 像素