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

Jab*_*Jab 36 iphone nsstring uiimage

我想NSString在a中绘制变量的内容UIImage,但我完全不知道如何做到这一点.我需要编写一个接收NSStringas参数的方法,并返回一个UIImage带有文本的方法.

rpm*_*pmx 89

你可以试试这个:(针对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;
}
Run Code Online (Sandbox Code Playgroud)

打电话给它:

UIImage *image = [self imageFromText:@"This is a text"];
Run Code Online (Sandbox Code Playgroud)

  • 对于iOS4 +,您应该创建缩放0.0的上下文,以便在缩放不是1.0时获得主屏幕的缩放(视网膜显示为2.0):UIGraphicsBeginImageContextWithOptions(size,NO,0.0); (7认同)
  • @PsychoDad在[text drawAtPoint]行之前在UIColor上调用-set.像这样:[[UIColor redColor] set]; (2认同)

Bao*_*Lei 14

添加Swift版本,还为您提供了更多选择:

class func sizeOfAttributeString(str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
    let size = str.boundingRectWithSize(CGSizeMake(maxWidth, 1000), options:(NSStringDrawingOptions.UsesLineFragmentOrigin), context:nil).size
    return size
}

class func imageFromText(text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage {
    let paragraph = NSMutableParagraphStyle()
    paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
    paragraph.alignment = .Center // potentially this can be an input param too, but i guess in most use cases we want center align

    let attributedString = NSAttributedString(string: text, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName:paragraph])

    let size = sizeOfAttributeString(attributedString, maxWidth: maxWidth)
    UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
    attributedString.drawInRect(CGRectMake(0, 0, size.width, size.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
Run Code Online (Sandbox Code Playgroud)