Подтвердить что ты не робот

Как преобразовать текст в изображение?

Я пытаюсь написать функцию для преобразования текста текстового поля в образ (пример). Я попытался найти пример, большая часть образца также перезаписывает текст на изображении. Можно ли привести несколько примеров или подсказок о том, как это сделать?

4b9b3361

Ответ 1

Возможны несколько подходов.

  • Если у вас есть существующие UITextField, UITextView или UILabel, которые вы просто хотите отображать в качестве изображения, вы можете использовать традиционные подходы к снимкам, например:

    - (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];
    
  • Если вам нужно поддерживать более ранние версии 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;
    }
    

Существует много перестановок каждого из них. Это просто зависит от того, чего вы пытаетесь достичь.


Другой подход состоит в том, чтобы просто иметь объекты UIImageView и UILabel/UITextView в представлении, а если у вас есть изображение с сервера, задайте образ UIImageView и текста, установите text UILabel/UITextView.

Ответ 2

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

Вы можете начать с этого

Ответ 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 можно найти здесь. После этого просмотра с текстом на нем преобразуйте его в UIImage с помощью этой техники.

Ответ 4

Быстрый ответ

Если вам нужно только получить изображение видимого содержимого UIFieldView, UITextView или UILabel, вы можете использовать следующий метод.

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
}

Примечания

  • Можно также просто изменить размер исходного текстового вида, а затем снова изменить его размер. Однако было проще просто сделать временную копию.
  • Другой способ получить копию представления - архивировать и разблокировать его.
  • Или вы можете просто написать прямо в UIImage.

Ответ 5

Это просто. Вы хотите преобразовать текст в UIImage. Просто draw text view 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

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 - это мой словарь, где я получил все свои данные).

Ответ 7

Он выравнивает версию.

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