两种方法实现UILabel的图文并茂的显示html文本

概述

本文讲述用2中方法在UILabel中显示带图片和文字的HTML文本。
先预览下显示效果:

显示效果

如果你的设备时iOS 9或以上,默认只允许HTTPS,请打开HTTP请求许可,参照:iOS 9打开HTTP请求许可

方案一:

//HTML文本 包含图片、文本
NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>&nbsp&nbsp花羊羊领取了你的<font color = \"red\"><a>红包</a></font>"
UILabel *label=[UILabel alloc] initWithFrame:CGRectMake(50, 200, 220, 20)];
[self.view addSubview:label];
UIFont *font=[UIFont systemFontOfSize:14];
label.font=font;
NSDictionary *optoins=@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
                            NSFontAttributeName:font};
NSData *data=[htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSAttributedString *attributeString=[[NSAttributedString alloc] initWithData:data
                                                                     options:optoins
                                                          documentAttributes:nil
                                                                       error:nil];
label.attributedText=attributeString;

方案一点评:

这种方案只是实现了显示,显示效果好不好是另一回事。事实证明,这种方案的显示效果很不好:

方案一显示效果

我们现在要对方案一进行优化。

方案一优化思路:

  • 1.缩小图片,让图片与字体显示差不多大;
  • 2.让字体显示垂直方向居中。

优化后的方案一:

//HTML文本 包含图片、文本
NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>&nbsp&nbsp花羊羊领取了你的<font color = \"red\"><a>红包</a></font>"
//我们可以先把src对应的图片解析出来,放到本地
NSRange httpRange=[htmlString rangeOfString:@"http://"];
NSRange endRange=[htmlString rangeOfString:@".png"];
NSString *picString=[htmlString substringWithRange:NSMakeRange(httpRange.location, endRange.location+endRange.length-httpRange.location)];
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:picString] options:nil progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
    //按照字体大小缩小图片,具体实现在下文
     UIImage *scaledImage=[self scaleImage:image font:font];
     NSData *imgData=UIImagePNGRepresentation(scaledImage);
     NSString *libPath=[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,     NSUserDomainMask, YES) lastObject];
    NSString *cachePath=[libPath stringByAppendingPathComponent:@"Caches"];
    NSString *scaledImagesPath=[cachePath stringByAppendingPathComponent:@"scaledImages"];
    if(![[NSFileManager defaultManager] fileExistsAtPath:scaledImagesPath]){
        [[NSFileManager defaultManager] createDirectoryAtPath:scaledImagesPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *picName=[[picString componentsSeparatedByString:@"/"] lastObject];
    NSString *filePath=[scaledImagesPath stringByAppendingPathComponent:picName];
    [imgData writeToFile:filePath atomically:YES];
    NSString *path=[NSURL fileURLWithPath:filePath].absoluteString;
    //用本地的图片路径替换远程图片路径
    htmlString=[htmlString stringByReplacingOccurrencesOfString:picString withString:path];
}];
UILabel *label=[UILabel alloc] initWithFrame:CGRectMake(50, 200, 220, 20)];
[self.view addSubview:label];
UIFont *font=[UIFont systemFontOfSize:14];
label.font=font;
NSDictionary *optoins=@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
                            NSFontAttributeName:font};
NSData *data=[htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSAttributedString *attributeString=[[NSAttributedString alloc] initWithData:data
                                                                     options:optoins
                                                          documentAttributes:nil
                                                                       error:nil];
label.attributedText=attributeString;
优化后的方案一显示效果

优化后的方案一点评

优化后的方案一显示效果差强人意。这种方法成功的解决了图片大小的问题,以及文本不居中的问题,但图片没有居中对齐,网上也找不到方法,只有继续探寻。

方案二:

//HTML文本 包含图片、文本
NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>&nbsp&nbsp花羊羊领取了你的<font color = \"red\"><a>红包</a></font>"
//我们可以先把src对应的图片解析出来,放到本地
NSRange httpRange=[htmlString rangeOfString:@"http://"];
NSRange endRange=[htmlString rangeOfString:@".png"];
NSString *picString=[htmlString substringWithRange:NSMakeRange(httpRange.location, endRange.location+endRange.length-httpRange.location)];
UIImage *scaledImage;
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:picString] options:nil progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
    //按照字体大小缩小图片,具体实现在下文
     scaledImage=[self scaleImage:image font:font];
     NSData *imgData=UIImagePNGRepresentation(scaledImage);
     NSString *libPath=[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,     NSUserDomainMask, YES) lastObject];
    NSString *cachePath=[libPath stringByAppendingPathComponent:@"Caches"];
    NSString *scaledImagesPath=[cachePath stringByAppendingPathComponent:@"scaledImages"];
    if(![[NSFileManager defaultManager] fileExistsAtPath:scaledImagesPath]){
        [[NSFileManager defaultManager] createDirectoryAtPath:scaledImagesPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *picName=[[picString componentsSeparatedByString:@"/"] lastObject];
    NSString *filePath=[scaledImagesPath stringByAppendingPathComponent:picName];
    [imgData writeToFile:filePath atomically:YES];
    //用空字符串替换远程图片路径
    htmlString=[htmlString stringByReplacingOccurrencesOfString:picString withString:@""];
}];
UILabel *label=[UILabel alloc] initWithFrame:CGRectMake(50, 200, 220, 20)];
[self.view addSubview:label];
UIFont *font=[UIFont systemFontOfSize:14];
label.font=font;
//利用NSTextAttachment文UILabel添加图片,并调整位置实现居中对齐
NSTextAttachment *attach=[[NSTextAttachment alloc] init];
attach.bounds=CGRectMake(2, -(label.frame.size.height-font.pointSize)/2, 12, 14);
attach.image=scaledImage;
NSMutableAttributedString *componets=[[NSMutableAttributedString alloc] init];
NSAttributedString *imagePart=[NSAttributedString attributedStringWithAttachment:attach];
[componets appendAttributedString:imagePart];
NSDictionary *optoins=@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
                            NSFontAttributeName:font};
NSData *data=[htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSAttributedString *textPart=[[NSAttributedString alloc] initWithData:data
                                                                     options:optoins
                                                          documentAttributes:nil
                                                                       error:nil];
[componets appendAttributedString:textPart];
label.attributedText=componets;
方案二的显示效果

方案二点评:

方案二显示效果略复杂,但是达到了我们需要的正常显示效果。
最后,附上根据字体大小缩小图片的方法:

-(UIImage *)scaleImage:(UIImage *)origin font:(UIFont *)font{
    
    CGFloat imgH=origin.size.height;
    CGFloat imgW=origin.size.width;
    CGFloat width;
    CGFloat height;
    CGFloat fontHeight=font.pointSize;
    if(imgW>imgH){
        
        width=fontHeight;
        height=fontHeight/imgW*imgH;
    }
    else{
        height=fontHeight;
        width=fontHeight/imgH*imgW;
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [origin drawInRect:CGRectMake(0, 0, width, height)];
    UIImage *scaledImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,188评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,464评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,562评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,893评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,917评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,708评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,430评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,342评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,801评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,976评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,115评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,804评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,458评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,008评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,135评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,365评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,055评论 2 355

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,178评论 25 707
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,754评论 1 92
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,107评论 4 62
  • 看到这个标题的时候,是不是以为我会告诉大家列生命清单的好处,以及怎样列好生命清单。但是我要很肯定的告诉你,都不是,...
    蓝莓姑娘阅读 1,281评论 6 2
  • 上次卸载是因为APP总是打不开,索性就清理掉了。大概一年后,为了要和京东图书比价,又重新下载,但也没在当当上面买,...
    Mr__Pan阅读 361评论 0 1