使用UITextView在NSAttributedString中自动调整图像

时间:2016-04-02 10:24:34

标签: ios swift uitextview nsattributedstring

我试图让UITextView显示包含图片的rtfd文档。问题是,图像与UITextView的框架重叠 - 它的宽度更大。我需要将此图像缩放到UITextView的宽度。这是我加载字符串的方式:

if let text = try? NSMutableAttributedString(URL: NSBundle.mainBundle().URLForResource("License agreement", withExtension: "rtfd")!, options: [NSDocumentTypeDocumentAttribute : NSRTFDTextDocumentType], documentAttributes: nil) {

        textView.attributedText = text
    }

我还尝试使用img style="width: 100%"的webarchive文件,但这也无效。

以这种方式显示rtfd或其他文档的最佳方法是什么,以便缩放图像以适应宽度?

2 个答案:

答案 0 :(得分:2)

感谢Larme对你的评论,我设法让它像这样工作:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    prepareTextImages()
}

private var text: NSMutableAttributedString?
private func prepareTextImages() {
    let width  = CGRectGetWidth(self.view.frame) - self.containerView.frame.origin.x * 2 - 10
    text?.enumerateAttribute(NSAttachmentAttributeName, inRange: NSRange(location: 0, length: text!.length), options: [], usingBlock: { [width] (object, range, pointer) in
        let textViewAsAny: Any = self.textView
        if let attachment = object as? NSTextAttachment, let img = attachment.imageForBounds(self.textView.bounds, textContainer: textViewAsAny as? NSTextContainer, characterIndex: range.location) {
            if attachment.fileType == "public.png" {
                let aspect = img.size.width / img.size.height
                if img.size.width <= width {
                    attachment.bounds = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
                    return
                }
                let height = width / aspect
                attachment.bounds = CGRect(x: 0, y: 0, width: width, height: height)
            }
        }
        })
}

这有一个小问题 - 滚动时我看到这个图像时有一个小的滞后。在不改变尺寸的情况下,全尺寸图像不会发生。有人会想到这个的原因吗?

答案 1 :(得分:0)

如果po textView的attributeText属性,您会发现它有很多这样的对象:

NSAttachment = "<NSTextAttachment: 0x6000002a39c0> \"XXXXXXX.jpg\"";
NSColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSFont = "<UICTFont: 0x7f8356400f60> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
NSKern = 0;
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 12, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 15/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0";
NSStrokeColor = "kCGColorSpaceModelRGB 0 0 0 1 ";
NSStrokeWidth = 0;  

然后您会发现NSTextAttachmentBingo。所以enum这些对象,获取NSTextAttachment并更改它的界限: (我将图像设置为右屏幕10px边距)

[attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {

            if (value) {

                if ([value isKindOfClass:[NSTextAttachment class]]) {

                    NSTextAttachment *attach = value;
                    CGFloat scale  = SCREEN_WIDTH / attach.bounds.size.width;
                    CGRect newRect = CGRectMake(attach.bounds.origin.x, attach.bounds.origin.y,SCREEN_WIDTH-10, attach.bounds.size.height*scale);
                    attach.bounds  = newRect;
                }
            }
        }];