图片展示需要添加代码:
htmlString = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@", imageWidth, htmlString];`
htmlString = [NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>%@", font.fontName, font.pointSize, htmlString];
示例:
+ (NSMutableAttributedString *)getAttributedStringByHTMLString:(NSString *)htmlString
imageWidth:(CGFloat)imageWidth
textAligment:(NSTextAlignment)textAligment
lineBreakMode:(NSLineBreakMode)lineBreakMode
lineSpacing:(CGFloat)lineSpacing
font:(UIFont *)font
color:(nullable UIColor *)color {
if (imageWidth > 0 && [htmlString containsString:@"<img"]) {
htmlString = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@", imageWidth, htmlString];
}
if (font) { //因为设置了font,不能再使用NSFontAttributeName属性来设置,加粗字体等样式会被覆盖掉
htmlString = [NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>%@", font.fontName, font.pointSize, htmlString];
}
NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding) };
NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = lineBreakMode;
[paragraphStyle setLineSpacing:lineSpacing];
[paragraphStyle setAlignment:textAligment];
NSRange range = NSMakeRange(0, [attributedString length]);
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
if (color) {
[attributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
return attributedString;
}