iOS图文混排图片处理

作者: 一只知更鸟的人生 | 来源:发表于2017-02-09 10:55 被阅读2379次

    写图文混排时会遇到一个问题,我的图片是从网络上下载的,所以预先不知道图片的大小,但是NSTextAttachment是需要设定大小的,所以一开始就用的placeholder图片的大小,等图片下载完成候再更新NSTextAttachment的bounds。

    UIImage*image = [UIImageimageNamed:@"placeholder.png"];

    NSTextAttachment*imgAttachment = [[NSTextAttachmentalloc]init];

    imgAttachment.image = image;

    CGSizeimageSize =CGSizeMake(SCREEN_WIDTH-10,200);

    imgAttachment.bounds =CGRectMake(0,0, imageSize.width, imageSize.height);

    NSMutableAttributedString*imgAttributedString = [[NSMutableAttributedStringalloc]initWithAttributedString:[NSAttributedStringattributedStringWithAttachment:imgAttachment]];

    [imgAttributedString addAttributes:self.tagAttributeDictionary[@"img"] range:NSMakeRange(0, imgAttributedString.length)];

    [attributedString appendAttributedString:imgAttributedString];

    NSURL*imgURL = [[NSURLalloc]initWithString:[element objectForKey:@"src"]];

    [_sdManager downloadImageWithURL:(NSURL*)imgURL options:0progress:^(NSIntegerreceivedSize,NSIntegerexpectedSize) {

    } completed:^(UIImage*image,NSError*error, SDImageCacheType cacheType,BOOLfinished,NSURL*imageURL) {

    imgAttachment.bounds =CGRectMake(0,0, SCREEN_WIDTH-10, image.size.height/(image.size.width/(SCREEN_WIDTH-10)));

    imgAttachment.image = image;

    }];

    但是当图片载入完成后,图片的大小还是原来的placeholder图片的大小,并没有按照设定后的大小显示,但是你如果重新退出这个ViewController再进入的话,图片神奇般的重新显示了。所以十有八九是TextView没有刷新的缘故了。如果调用textView的setNeedsLayout是没有用的,这个方法的用途是用来刷新subView的,对于TextView中的内容布局是没有影响的。

    所以我们要用到的是CoreText中的NSLayoutManager,先看一下我们要用到的方法

    invalidateLayoutForCharacterRange:actualCharacterRange:

    定义 Invalidates the layout information for the glyphs mapped to the given range of characters.

    这个方法会调用下面的方法

    1 imageForBounds:textContainer:characterIndex: will be called again.

    2 attachmentBoundsForTextContainer:[…]Index: will be called again.

    所以调用TextView的LayoutManager的这个方法的话可以使TextAttachment的大小刷新,我们利用delegate,每当图片载入完成,调用delegate的方法去刷新textView,这样就能够让图片正常显示了。

    NSURL*imgURL = [[NSURLalloc]initWithString:[element objectForKey:@"src"]];

    [_sdManager downloadImageWithURL:(NSURL*)imgURL options:0progress:^(NSIntegerreceivedSize,NSIntegerexpectedSize) {

    } completed:^(UIImage*image,NSError*error, SDImageCacheType cacheType,BOOLfinished,NSURL*imageURL) {

    imgAttachment.bounds =CGRectMake(0,0, SCREEN_WIDTH-10, image.size.height/(image.size.width/(SCREEN_WIDTH-10)));

    DebugLog(@"%f %f",imgAttachment.bounds.size.width,imgAttachment.bounds.size.height);

    imgAttachment.image = image;

    [self.delegate refreshTextViewAtRange:range];

    }];

    引用cookiezby.com/2016/07/13/iOS%E5%9B%BE%E6%96%87%E6%B7%B7%E6%8E%92%E5%88%B7%E6%96%B0%E5%9B%BE%E7%89%87%E5%A4%A7%E5%B0%8F/

    stackoverflow.com/questions/24509660/redrawing-nstextattachments-in-an-uitextview-with-attributed-text

    相关文章

      网友评论

        本文标题:iOS图文混排图片处理

        本文链接:https://www.haomeiwen.com/subject/qvliittx.html