微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cocoa – 如何从NSAttributedString获取图像数据

我有一个NSTextView.我将图像粘贴到其中并查看.当我获得文本视图的NSAttributedString的NSTextAttachment时,它的文件包装器为nil.如何获取粘贴到文本视图中的图像数据?

我在NSAttributedString上使用类别来获取文本附件.如果可能的话,我宁愿不写入磁盘.

- (NSArray *)allAttachments
{
    NSError *error = NULL;
    NSMutableArray *theAttachments = [NSMutableArray array];
    NSRange theStringRange = NSMakeRange(0,[self length]);
    if (theStringRange.length > 0)
    {
        NSUInteger N = 0;
        do
        {
            NSRange theEffectiveRange;
            NSDictionary *theAttributes = [self attributesAtIndex:N longestEffectiveRange:&theEffectiveRange inRange:theStringRange];
            NSTextAttachment *theAttachment = [theAttributes objectForKey:NSAttachmentAttributeName];
            if (theAttachment != NULL){
                NSLog(@"filewrapper: %@",theAttachment.fileWrapper);
                [theAttachments addobject:theAttachment];
            }
            N = theEffectiveRange.location + theEffectiveRange.length;
        }
        while (N < theStringRange.length);
    }
    return(theAttachments);
}

解决方法

>枚举附件. [NSTextStorage enumerateAttribute:…]
>获取附件的文件包装器.
>写一个URL.

[textStorage enumerateAttribute:NSAttachmentAttributeName
                        inRange:NSMakeRange(0,textStorage.length)
                        options:0
                     usingBlock:^(id value,NSRange range,BOOL *stop)
 {
     NSTextAttachment* attachment = (NSTextAttachment*)value;
     NSFileWrapper* attachmentWrapper = attachment.fileWrapper;
     [attachmentWrapper writetoURL:outputURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:nil];
     (*stop) = YES; // stop so we only write the first attachment
 }];

此示例代码仅将第一个附件写入outputURL.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐