TYAttributedLabel聊天列表显示gif总结;【聊天动态图,GIF图,iOS,TYAttributedLabel】
一、WebView加载;可以通过WebView加载本地gif图和网络gif图,但图片大小不能自适应控件大小,也不能设置gif图播放时间。
- (UIView *)webViewGif{
UIWebView*webView = [[UIWebView alloc] init];
// 本地地址
NSString *localPath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"gif"];
//网络地址
NSString *imagePath = @"https://www.baidu..com/xxxxx.gif";
NSURL*imageUrl = [NSURLURLWithString:imagePath];
NSURLRequest*request = [NSURLRequest requestWithURL:imageUrl];
[webView loadRequest:request];
}
二、UIImageView加载多图动画;把动态图拆分成一张张图片,将一系列帧添加到animationImages数组里面,然后设置animation一系列属性,如动画时间,动画重复次数。
- (UIView *)imageViewGif {
UIImageView *imageView = [[UIImageView alloc] init];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
for(inti =0; i < images.count; i++)
{
NSString*imagePath = [NSString stringWithFormat:@"path_%d",i +1];
UIImage *image = [UIImage imageNamed:imagePath];
[images addObject:image];
}
imageView.animationImages = images;
imageView.animationDuration =2;
[imageView startAnimating];
return imageView;
}
三、SDWebImage加载本地gif;在SDWebImage这个库里有一个UIImage+GIF的类别,使用sd_animatedGIFWithData方法可以将GIF图片数据专为图片。
- (UIView *)sd_imageViewGif {
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"gif"];
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage sd_animatedGIFWithData:imageData];
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = image;
return imageView;
}
四、FLAnimatedImage使用
FLAnimatedImage 是由Flipboard开源的iOS平台上播放GIF动画的一个优秀解决方案,在内存占用和播放体验都有不错的表现。FLAnimatedImage项目的流程比较简单,FLAnimatedImage就是负责GIF数据的处理,然后提供给FLAnimatedImageView一个UIImage对象。FLAnimatedImageView拿到UIImage对象显示出来就可以了。
- (UIView *)animatedImageGif {
FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"hello" withExtension:@"gif"];
NSData*data = [NSData dataWithContentsOfURL:url];
FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:data];
imageView.animatedImage = animatedImage;
return imageView;
}
有了上面几个加载gif的方法我们就可以很好的显示在聊天内容上面了,TYAttributedLabel是一个很好的图文并排显示框架,这也是选择demo的原因;
TYViewStorage 里面有个view属性,我们只要给view赋值就可以显示我们想要显示的gif
- (void)showGifInView{
TYAttributedLabel *tyLabel = [[TYAttributedLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
NSMutableArray *gifs = [NSMutableArray array];
for (int i = 0; i < 4; i++) {
TYViewStorage *tyViewStorage = [[TYViewStorage alloc] init]; // 读取gif图片数据
tyViewStorage.range = NSMakeRange(0, 10);
tyViewStorage.size = CGSizeMake(32, 32);
UIView *gifView = [self webViewGif];
// UIView *gifView = [self imageViewGif];
// UIView *gifView = [self sd_imageViewGif];
// UIView *gifView = [self animatedImageGif];
[gifs addObject:tyViewStorage];
}
[tyLabel addTextStorageArray:gifs];
}
大功告成!