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

Posted

技术标签:

【中文标题】如何在 iOS 上将文本转换为图像?【英文标题】:How to convert text to Image on iOS? 【发布时间】:2014-05-09 03:49:05 【问题描述】:

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

【问题讨论】:

我需要这个功能是因为我从服务器获取数据。如果数据有图像,则 UIIMAGEView 将显示图像,但如果没有图像,则我需要将部分内容转换为图像并显示在 UIIMAGEVIEW 上。 在这里看看我的解决方案。斯威夫特 3:Converting Text to UIImage ios 请参阅my Swift 4 / iOS 11 answer for a similar question,其中显示了多达 6 种将文本转换为图像(或视图)以进行显示的不同方法。 【参考方案1】:

有几种方法是可能的。

    如果您有一个现有的UITextFieldUITextViewUILabel,您只想将其渲染为图像,则可以采用传统的快照方法,例如:

    - (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;
    
    

    如果你想要一个通用的“从文本创建图像”例程,在 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];
    

    如果您需要支持早期的 iO​​S 版本,您可以使用此技术:

    - (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;
    
    

每一个都有很多很多排列。这仅取决于您要达到的目标。


另一种方法是在视图中简单地同时拥有UIImageViewUILabel/UITextView 对象,如果您有来自服务器的图像,则设置UIImageView 的图像和文本,设置textUILabel/UITextView

【讨论】:

不错的答案!如果您需要将彩色文本转换为可着色的图像,例如一个 UIBarButtonItem,你有两个选择:1)设置项目的色调颜色,如:[buttonItem setTintColor:color]; 2)在返回uiimage之前指定渲染模式,如:return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; @Rob 虽然这是一个非常古老的答案......我想从你的答案中实施选项(3)。但它的放置文本左对齐。我怎样才能使它居中对齐?我只想要图像中的两个字母。 为什么不选择选项 2?在这种情况下,您有***.com/a/477658/1271826。如果您不这样做,则必须手动计算一行文本将采用的边界矩形,然后将绘制它的位置的origin 偏移适当的量。选项 2 更容易。【参考方案2】:
NSString *string = @"Some text";
UIGraphicsBeginImageContext(CGSizeMake(80, 50));
[string drawAtPoint:CGPointMake(10, 20)
           withFont:[UIFont systemFontOfSize:12]];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

你可以从这个开始

【讨论】:

【参考方案3】:

快速回答

如果您只需要获取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】:

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

@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*/];

更多关于绘图的信息NSStrings can be found here。获得带有文本的视图后,将其转换为 UIImage with this technique。

【讨论】:

【参考方案5】:

这很简单。您想将文本转换为 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;

【讨论】:

【参考方案6】:

居中对齐版本。

- (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.

【讨论】:

【参考方案7】:
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 是我获取所有数据的字典)。

【讨论】:

以上是关于如何在 iOS 上将文本转换为图像?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 上将 MS Office DOC/XLS/PPT 和 PDF 转换为图像

如何在Android上将图像字符串转换为整数?

在 Android 上将 Web 图像转换为 ListView

在 iOS 上将图像保存为连拍

在 iOS 上将图像和文本内联居中

如何在 ios7 上将导航栏背景图像添加到 MFMailComposeViewController