从NSAttributed字符串中提取UIImage

Yogesh lolusare

我正在做的是:

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

询问:

如何从NSATTRIBUTED STRING获取图像;

  • UIIMAGE =来自NSATTRIBUTED STRING;
  • ARRAYOFIMAGE =来自NSTRTRIBUTED STRING;
眼泪

您必须枚举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];
    }
}];

如您所见,这里有测试if ([attachment image])那是因为似乎如果您创建了NSTextAttachment与之放置的内容,NSAttachmentAttributeName并且您的图像就会在那里。但是,例如,如果您使用网络上的图像并将其转换为NSTextAttachmentHTML代码中的图像,[attachment image]则将为nil并且您将无法获得该图像。

您可以看到使用断点在这个片段中(与设置真实图像URL和捆绑的真实图像名称的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]];

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章