概述
本文講述用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>  花羊羊領取了你的<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;
方案一點評:
這種方案只是實現(xiàn)了顯示,顯示效果好不好是另一回事住练。事實證明地啰,這種方案的顯示效果很不好:
方案一顯示效果
我們現(xiàn)在要對方案一進行優(yōu)化。
方案一優(yōu)化思路:
- 1.縮小圖片讲逛,讓圖片與字體顯示差不多大亏吝;
- 2.讓字體顯示垂直方向居中。
優(yōu)化后的方案一:
//HTML文本 包含圖片盏混、文本
NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>  花羊羊領取了你的<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) {
//按照字體大小縮小圖片,具體實現(xiàn)在下文
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;
優(yōu)化后的方案一顯示效果
優(yōu)化后的方案一點評
優(yōu)化后的方案一顯示效果差強人意许赃。這種方法成功的解決了圖片大小的問題止喷,以及文本不居中的問題,但圖片沒有居中對齊混聊,網(wǎng)上也找不到方法弹谁,只有繼續(xù)探尋。
方案二:
//HTML文本 包含圖片句喜、文本
NSString *htmlString=@"< img src=http://upload-images.jianshu.io/upload_images/937405-50a8ad2d8866fc12.png>  花羊羊領取了你的<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) {
//按照字體大小縮小圖片,具體實現(xiàn)在下文
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添加圖片咳胃,并調(diào)整位置實現(xiàn)居中對齊
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;
方案二的顯示效果
方案二點評:
方案二顯示效果略復雜植康,但是達到了我們需要的正常顯示效果。
最后拙绊,附上根據(jù)字體大小縮小圖片的方法:
-(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;
}