美文网首页iOS技术专题开发中有帮助的iOS文章iOS个人修养
两种方法实现UILabel的图文并茂的显示html文本

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

作者: CGPointZero | 来源:发表于2016-08-17 17:17 被阅读6035次

    概述

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

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

    方案一:

    //HTML文本 包含图片、文本
    NSString *htmlString=@"< img src=http:https://img.haomeiwen.com/i937405/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:https://img.haomeiwen.com/i937405/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:https://img.haomeiwen.com/i937405/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;
    }
    

    相关文章

      网友评论

      • James_Hy:有几个问题:
        1. label 富文本解析 html ,是后端返回的呢, 布局自适应的,怎么处理呢?
        2. 下载图片本身是异步进行的, 直接在 block 下面赋值如果为 空 呢?
        CGPointZero:自动布局只需要布局label就可以了
        如果为空,你可以搞一个placeHolder,或者直接显示空白
      • Echo126:NSString *htmlStr =@"<span class='highlightTag'>我</span>热爱演讲!<span class='highlightTag'>我</span>为中国代言!";
        您好,上边这种html怎么设置“我”是高亮,其他为普通颜色,然后所有的字体都是指定的[UIFont systemFontOfSize:18] 用label显示出来 ? 我现在是<font color=#55a8fd>把<span class='highlightTag'>,</span> 分别用<font color=#55a8fd>和</font>替换掉了。然后显示“我”都是高亮的,但是字体大小改不了。
        CGPointZero:你没指定size啊,<font size = 36
      • 云无心:楼主代码有一个空格,导致问题
      • a42b417881b1:好像指定 img 标签的 width 属性就可以了,不用那么麻烦使用SD去下去图片
        孤独感爆棚:能看下你的怎么处理的吗?
      • 1382806c226a:用富文本不行吗?
        五高:人家用的不就是富文本吗?

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

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