NSMutableAttributedString *attStr = [NSMutableAttributedString new];
NSString *style = [NSString stringWithFormat:@"<style> body { font-size: %@px; } p:last-of-type { margin: 0; }</style>", @(CLScaleValue(13))];
NSString *content = @"富文本内容";
NSString *styledHtml = [NSString stringWithFormat:@"%@%@", style, content];
[attStr appendAttributedString:[[NSAttributedString alloc] initWithData: [styledHtml dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil]];
//遍历富文本得到NSTextAttachment类,改变图片的大小
[attStr enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attStr.length) options:0 usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if ([value isKindOfClass:[NSTextAttachment class]]) {
NSTextAttachment * attachment = value;
CGFloat height = attachment.bounds.size.height;
CGFloat width = attachment.bounds.size.width;
CGFloat tempHeight = height/(width/(CLSCREENWIDTH-60));
//根据显示宽度进行等比缩放
attachment.bounds = CGRectMake(0, 0, CLSCREENWIDTH-60, tempHeight);
}
}];
解决IOS 显示富文本时,图片显示超出屏幕问题。
来源参考:https://www.jianshu.com/p/3243d8c130a2