UI提供一个图片转换Html,两种方法实现UILabel的图文并茂的显示html文本

概述

本文讲述用2中方法在UILabel中显示带图片和文字的HTML文本。

先预览下显示效果:

AAffA0nNPuCLAAAAAElFTkSuQmCC

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

方案一:

//HTML文本 包含图片、文本

NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>  花羊羊领取了你的红包"

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;

方案一点评:

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

AAffA0nNPuCLAAAAAElFTkSuQmCC

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

方案一优化思路:

1.缩小图片,让图片与字体显示差不多大;

2.让字体显示垂直方向居中。

优化后的方案一:

//HTML文本 包含图片、文本

NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>  花羊羊领取了你的红包"

//我们可以先把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;

AAffA0nNPuCLAAAAAElFTkSuQmCC

优化后的方案一点评

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

方案二:

//HTML文本 包含图片、文本

NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>  花羊羊领取了你的红包"

//我们可以先把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;

AAffA0nNPuCLAAAAAElFTkSuQmCC

方案二点评:

方案二显示效果略复杂,但是达到了我们需要的正常显示效果。

最后,附上根据字体大小缩小图片的方法:

-(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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的示例代码,可以在 Unity 和 NGUI实现显示带多个网络图片的富文本: ```csharp using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine.UI; public class RichText : MonoBehaviour { public UILabel label; public UIGrid imagesGrid; public GameObject imagePrefab; private List<string> urls = new List<string>(); // 正则表达式匹配网络图片的链接 private static readonly Regex UrlRegex = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); public void SetText(string text) { // 清空之前的图片 foreach (Transform child in imagesGrid.transform) { Destroy(child.gameObject); } // 获取所有网络图片的链接 urls.Clear(); MatchCollection matches = UrlRegex.Matches(text); foreach (Match match in matches) { string url = match.Value; if (url.EndsWith(".jpg") || url.EndsWith(".png")) { urls.Add(url); } } // 将所有网络图片添加到 imagesGrid 中 foreach (string url in urls) { GameObject imageObject = Instantiate(imagePrefab, imagesGrid.transform); StartCoroutine(LoadImage(url, imageObject.GetComponent<UITexture>())); } // 将文本内容设置到 label 上 label.text = text; } private IEnumerator LoadImage(string url, UITexture texture) { WWW www = new WWW(url); yield return www; if (www.error == null) { texture.mainTexture = www.texture; } else { Debug.LogError("Failed to load image: " + www.error); } } } ``` 使用方法: 1. 在 Unity 中创建一个 UI Root,添加一个 NGUI 的 Label 和 Grid。 2. 将 RichText 脚本挂载到 Label 上,将 imagesGrid 和 imagePrefab 拖拽到脚本对应的字段中。 3. 调用 `SetText()` 方法设置富文本内容即可,例如: ```csharp RichText richText = GetComponent<RichText>(); richText.SetText("这是一段带图片的富文本,<img src=\"http://example.com/image1.jpg\"> 和 <img src=\"http://example.com/image2.png\">"); ``` 这样,就可以在 NGUI实现显示带多个网络图片的富文本了。注意,这里使用了 HTML 标记 `<img>` 来指定图片的链接,这是一种常见的富文本格式。同时,也可以根据需要修改正则表达式来支持不同的富文本格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值