问题描述
我在做的是:
- NSATTRIBUTE STRING = NSSTRING + UIIMAGE;
- NSDATA = NSATTRIBUTED STRING;
- 我还能将nsdata转换为nsattributed字符串
- NSATTRIBUTED STRING = NSDATA:
- 然后从NSAttributed字符串中提取嵌套
- NSSTRING = [NSATTRIBUTED STRING string];
- NSATTRIBUTE STRING = NSSTRING + UIIMAGE's;
- NSDATA = NSATTRIBUTED STRING;
- ALSO I am able to convert nsdata to nsattributed string
- NSATTRIBUTED STRING = NSDATA:
- And then extracting nesting from NSAttributed string
- NSSTRING = [NSATTRIBUTED STRING string];
查询:
如何从NSATTRIBUTED STRING获取图像;
How can i get IMAGES from NSATTRIBUTED STRING;
- UIIMAGE =来自NSATTRIBUTED STRING;
- ARRAYOFIMAGE =来自NSATTRIBUTED STRING;
推荐答案
你必须枚举 NSAttributedString
寻找 NSTextAttachment
s。
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([附件图片] )
。那是因为看起来如果你创建 NSTextAttachment
与 NSAttachmentAttributeName
一起放置它会存在,你的图像就在那里。但是,如果您使用来自网络的图像并将其从HTML代码转换为 NSTextAttachment
,则 [附件图片]
将为零,您将无法获得图像。
As you can see, there is the test if ([attachment image])
. That's because it seems that if you created the NSTextAttachment
to put with NSAttachmentAttributeName
it will exist and your image will be there. But if you use for example an image from the web and convert it as a NSTextAttachment
from a HTML code, then [attachment image]
will be nil and you won't be able to get the image.
您可以看到在此片段中使用断点(设置实际图像URL和真实来自包的图像名称。
NSString * htmlString = @http:// anImageURL \> Blahttp:// anOtherImageURL \>测试重新测试;
You can see using breakpoints with this snippet (with setting real image URL and an real image name from bundle. NSString *htmlString = @"http://anImageURL\">Blahttp://anOtherImageURL\"> Test retest";
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]];
这篇关于从NSAttributed String中提取UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!