从NSAttributed String中提取UIImage

Yog*_*are 4 uiimage nsattributedstring ios

我在做的是:

  1. NSATTRIBUTE STRING = NSSTRING + UIIMAGE;
  2. NSDATA = NSATTRIBUTED STRING;
  3. 我也能将nsdata转换为nsattributed字符串
  4. NSATTRIBUTED STRING = NSDATA:
  5. 然后从NSAttributed字符串中提取嵌套
  6. NSSTRING = [NSATTRIBUTED STRING string];

查询:

如何从NSATTRIBUTED STRING获取图像;

  • UIIMAGE =来自NSATTRIBUTED STRING;
  • ARRAYOFIMAGE =来自NSATTRIBUTED STRING;

Lar*_*rme 14

你必须列举NSAttributedString寻找NSTextAttachments.

NSMutableArray *imagesArray = [[NSMutableArray alloc] init];
[attributedString enumerateAttribute:NSAttachmentAttributeName
                             inRange:NSMakeRange(0, [attributedString length])
                             options:0
                          usingBlock:^(id value, NSRange range, BOOL *stop)
{
    if ([value isKindOfClass:[NSTextAttachment class]])
    {
    NSTextAttachment *attachment = (NSTextAttachment *)value;
    UIImage *image = nil;
    if ([attachment image])
        image = [attachment image];
    else
        image = [attachment imageForBounds:[attachment bounds]
                             textContainer:nil
                            characterIndex:range.location];

    if (image)
        [imagesArray addObject:image];
    }
}];
Run Code Online (Sandbox Code Playgroud)

如您所见,有测试if ([attachment image]).这是因为它看来,如果你创建了NSTextAttachment与把NSAttachmentAttributeName它存在,你的形象将在那里.但是,如果您使用来自网络的图像并将其转换为NSTextAttachmentHTML代码,那么[attachment image]将为零,您将无法获得图像.

您可以看到在此片段中使用断点(设置实际图像URL和来自bundle的真实图像名称.NSString*htmlString = @"http:// anImageURL \"> Blahttp:// anOtherImageURL \">测试重新测试 ";

NSError *error;
NSAttributedString *attributedStringFromHTML = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                                                                options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
                                                                                          NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}
                                                                     documentAttributes:nil
                                                                                  error:&error];

NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
[textAttachment setImage:[UIImage imageNamed:@"anImageNameFromYourBundle"]];

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedStringFromHTML];
[attributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment]];
Run Code Online (Sandbox Code Playgroud)