UILabel上添加gif动态图

遇到一个新需求,需要在富文本上添加gif或者其他动态图,原来的使用的富文本不支持动态图,就研究下了国外大牛的demo,其实还是很简单的,主要原理就是把动态图切成一帧帧图片,然后利用NSTimer和动态图的周期循环在UILabel上画图片。。。但是亲测了一下不会引起cpu和内存方面的担忧,所以我们可以在第三方的富文本源码上进行修改或者重新封装一下,废话不多少,直接上代码。


1.拿gif为例,首先处理gif成图片数字和得到动画周期

 //测试 处理消息区 gif  得到 图片数组和动画周期 _images _duration

-(void)getImagesAndDuration{

       NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"gif"];

        NSData *data = [NSData dataWithContentsOfFile:path];

        CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);

        size_t count = CGImageSourceGetCount(source);

        _images = [NSMutableArray array];

        _duration = 0.0f;

        for (size_t i = 0; i < count; i++) {

            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);

            _duration += [self sd_frameDurationAtIndex:i source:source];

            [_images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];

            CGImageRelease(image);

        }

}


-(float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {

    float frameDuration = 0.1f;

    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);

    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;

    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];

    

    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];

    if (delayTimeUnclampedProp) {

        frameDuration = [delayTimeUnclampedProp floatValue];

    }

    else {

        

        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];

        if (delayTimeProp) {

            frameDuration = [delayTimeProp floatValue];

        }

    }

    

    // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值