美文网首页
修改HTML富文本中的图片的大小

修改HTML富文本中的图片的大小

作者: 黑暗森林的歌者 | 来源:发表于2018-09-01 18:16 被阅读451次

修改HTML富文本中的图片的大小

使用 UITextView或者UILabel显示HTML 的时候,如果其中有图片,但是图片大小并不是想要的大小,就需要过滤其中的图片资源,并修改size。

// htmlString 是获取的HTML字符串
// 通过标签过滤出来src图片资源
// 图片的链接,根据后台返回的地址,判断是否需要在这里进行拼接
NSString *regulaStr = @"<\\s*img\\s+[^>]*?src\\s*=\\s*[\'\"](.*?)[\'\"]\\s*(alt=[\'\"](.*?)[\'\"])?[^>]*?\\/?\\s*>";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
    
    NSArray *arrayOfAllMatches = [regex matchesInString:htmlString options:0 range:NSMakeRange(0, [htmlString length])];
    for (NSTextCheckingResult *match in arrayOfAllMatches) {
        NSRange range = match.range;
        range.location = 1;
        NSString* group1 = [htmlString substringWithRange:[match rangeAtIndex:1]];
        if (group1.length > 0) {
            htmlString = [htmlString stringByReplacingOccurrencesOfString:group1 withString:[[Utils ImgUrl:group1] absoluteString]];
        }
    }

// 将HTML字符串转为富文本
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
    
    NSAttributedString *attributeString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
    // 遍历富文本的附件
    [attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        if (value) {
            NSTextAttachment *ment = value;
            if (ment.bounds.size.width > 250) {// 假如图片宽度大于250,就设置为250,并且高度按照比例缩小
                CGFloat scale = 250 / ment.bounds.size.width;
                ment.bounds = CGRectMake(0, 0, scale * ment.bounds.size.width, scale * ment.bounds.size.height);
            }
        }
    }];

建议在生成数据model的时候执行size转换的代码

相关文章

网友评论

      本文标题:修改HTML富文本中的图片的大小

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