如何在iOS上将文本转换为图像?

时间:2014-05-09 03:49:06

标签: ios uiimage

我正在尝试编写一个函数来将文本字段文本转换为图像(example)。我试图搜索一个例子,大多数样本也是在图像上覆盖文本。是否可以给我一些示例或提示如何做到这一点?

7 个答案:

答案 0 :(得分:52)

有几种方法可行。

  1. 如果您只想将现有的UITextFieldUITextViewUILabel呈现为图片,则可以使用传统的快照方法,例如:< / p>

    - (UIImage *)imageForView:(UIView *)view
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
    
        if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
            [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];  // if we have efficient iOS 7 method, use it ...
        else
            [view.layer renderInContext:UIGraphicsGetCurrentContext()];         // ... otherwise, fall back to tried and true methods
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    
  2. 如果您想要一个通用的“从文本创建图像”例程,在iOS 7中,它看起来像:

    - (UIImage *)imageFromString:(NSString *)string attributes:(NSDictionary *)attributes size:(CGSize)size
    {
        UIGraphicsBeginImageContextWithOptions(size, NO, 0);
        [string drawInRect:CGRectMake(0, 0, size.width, size.height) withAttributes:attributes];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    

    以上将创建一个图像,其大小将根据文本而变化。显然,如果你只想要一个固定大小的图像,那么使用常量frame,而不是动态构建它。

    无论如何,你可以像上面那样使用上面的内容:

    NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    
    NSDictionary *attributes = @{NSFontAttributeName            : [UIFont systemFontOfSize:20],
                                 NSForegroundColorAttributeName : [UIColor blueColor],
                                 NSBackgroundColorAttributeName : [UIColor clearColor]};
    
    UIImage *image = [self imageFromString:string attributes:attributes size:self.imageView.bounds.size];
    
  3. 如果您需要支持早期的iOS版本,可以使用此技术:

    - (UIImage *)imageFromString:(NSString *)string font:(UIFont *)font size:(CGSize)size
    {
        UIGraphicsBeginImageContextWithOptions(size, NO, 0);
        [string drawInRect:CGRectMake(0, 0, size.width, size.height) withFont:font lineBreakMode: NSLineBreakByWordWrapping];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    
  4. 每种方法都有很多种排列。这取决于你想要达到的目标。


    另一种方法是在视图中同时拥有UIImageViewUILabel / UITextView个对象,如果您有来自服务器的图像,请设置{{1 }和文字,设置UIImageView / text的{​​{1}}。

答案 1 :(得分:9)

NSString *string = @"Some text";
UIGraphicsBeginImageContext(CGSizeMake(80, 50));
[string drawAtPoint:CGPointMake(10, 20)
           withFont:[UIFont systemFontOfSize:12]];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

你可以从这个

开始

答案 2 :(得分:3)

您可以尝试创建自己的自定义UIView子类,在其上绘制NSString(您的文字),然后将其转换为UIImage。您只能使用UIView方法在-drawRect:上绘制文字。这是你的子类的想法。

@interface TextView : UIView {
    NSString *_text;
}
- (id)initWithFrame:(CGRect)frame andText:(NSString *)text;
@end

@implementation TextView
- (id)initWithFrame:(CGRect)frame andText:(NSString *)text
{
    if (self = [super initWithFrame:frame]) {
        _text = text;
    }
    [self setNeedsDisplay]; // calls the -drawRect method
    return self;
}

- (void)drawRect:(CGRect)rect
{
    [_text drawAtPoint:/* location of text*/ 
        withAttributes:/* style    of text*/];
}

有关绘制NSString s can be found here的更多信息。获得此视图后,请将其转换为UIImage with this technique

答案 3 :(得分:2)

快速回答

如果您只需要获取UIFieldViewUITextViewUILabel的可见内容的图片,那么您可以使用以下方法。

func imageFromView(myView: UIView) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(myView.bounds.size, false, UIScreen.mainScreen().scale)
    myView.drawViewHierarchyInRect(myView.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

特殊情况

当文本内容滚出框架时,例如在UITextView中,上面的解决方案将仅捕获可见区域。为了获得所有内容,一种解决方案是在创建文本视图之前将文本视图的副本调整为其内容视图的大小。

func imageFromTextView(textView: UITextView) -> UIImage {

    // Make a copy of the textView first so that it can be resized 
    // without affecting the original.
    let textViewCopy = UITextView(frame: textView.frame)
    textViewCopy.attributedText = textView.attributedText

    // resize if the contentView is larger than the frame
    if textViewCopy.contentSize.height > textViewCopy.frame.height {
        textViewCopy.frame = CGRect(origin: CGPointZero, size: textViewCopy.contentSize)
    }

    // draw the text view to an image
    UIGraphicsBeginImageContextWithOptions(textViewCopy.bounds.size, false, UIScreen.mainScreen().scale)
    textViewCopy.drawViewHierarchyInRect(textViewCopy.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

备注

  • 还可以调整原始文本视图的大小,然后再将其重新调整大小。但是,制作临时副本似乎更简单。
  • 获取视图副本的另一种方法是archive and unarchive it
  • 或者你可以直接写一个UIImage

答案 4 :(得分:1)

很简单。您想要将文本转换为UIImage。只需draw text view's layer into Image context并转换为UIImage。代码如下。

+ (UIImage *) imageWithView:(UITextView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

答案 5 :(得分:0)

NSString * ImgString = [[[self.dataDict valueForKey:@"newsItems"]objectAtIndex:indexPath.row]valueForKey:@"image"];

NSURL *imageURL = [NSURL URLWithString:ImgString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

cell.imageLabel.image = image;

我想在表视图中呈现,所以我在单元格中为索引路径的行编写此代码。

(dataDict是我获取所有数据的字典)。

答案 6 :(得分:0)

它是居中对齐版本。

- (UIImage *)imageFromString:(NSString *)string size:(CGSize)size
{
    NSDictionary *attributes = @{NSFontAttributeName            : [UIFont systemFontOfSize:18],
                                 NSForegroundColorAttributeName : [UIColor whiteColor],
                                 NSBackgroundColorAttributeName : [UIColor redColor]
                                 };    

    UIGraphicsBeginImageContext(size);
    CGRect txtRect = [string boundingRectWithSize:CGSizeZero
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:attributes
                                       context:nil];

    [string drawAtPoint:CGPointMake(size.width/2 - txtRect.size.width/2, size.height/2 - txtRect.size.height/2) withAttributes:attributes];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

以这种方式使用

NSString *string = @"A";

UIImage *image = [self imageFromString:string size:imgView.bounds.size];
[imgView.bounds setImage:image];
[imgView.bounds setBackgroundColor:[UIColor redColor];//Full margin with same color of text image color.