使用UILabel之attributeText属性,展示H5代码片段,实现富文本效果。
遇到问题:图片尺寸和屏幕尺寸不匹配,这就要求调整h5代码片段中图片标签中图片尺寸, 实现如下:
@implementation AttributeTools
/**
Filter H5字符串中的图片标签,自定义图片宽度。
@param width 宽度
@return result
*/
+(NSString *)pointSizeOfImageInHtml_Str:(NSString*)str Width:(CGFloat)width{
if (str == nil || str.length == 0) { return @""; }
NSString *content = [str stringByReplacingOccurrencesOfString:@"&quot" withString:@"'"];
content = [content stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
content = [content stringByReplacingOccurrencesOfString:@">" withString:@">"];
content = [content stringByReplacingOccurrencesOfString:@""" withString:@"\""];
NSString *html = content;
NSString * regExpStr = @"<(img|IMG)[^\\<\\>]*>";
NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:regExpStr options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *matches=[regex matchesInString:html
options:0
range:NSMakeRange(0, [html length])];
//H5中<img ...... />标签数组
NSMutableArray *imgArray = [NSMutableArray array];
NSMutableArray *urlArray = [NSMutableArray array];
for (NSTextCheckingResult *result in matches) {
NSRange range = result.range;
NSString *group = [html substringWithRange:range];
NSRange srange1 = [group rangeOfString:@"http"];
NSString *tempString1 = [group substringWithRange:NSMakeRange(srange1.location, group.length - srange1.location)];
NSRange srange2 = [tempString1 rangeOfString:@"\""];
NSString *tempString2 = [tempString1 substringWithRange:NSMakeRange(0,srange2.location)];
[urlArray addObject:tempString2];
[imgArray addObject:group];
}
for (int i = 0; i < imgArray.count; i++) {
NSString *string = imgArray[i];
html = [html stringByReplacingOccurrencesOfString:string withString:[NSString stringWithFormat:@"<img src=\"%@\" title=\"\" alt=\"%ld\" width=\"%f\" height=\"auto\">",urlArray[i],[self getNowTimeTimestamp]+i,width]];
}
return html;
}
+(long)getNowTimeTimestamp{
NSDate *datenow = [NSDate date];
return (long)[datenow timeIntervalSince1970];
}
@end