iOS:长图切割并转为动画gif——精灵表单sprite Sheet的转化

iOS:长图切割并转为动画gif——精灵表单sprite Sheet的转化

通常的,iOS显示gif可以将文件转为NSData后再对其进行解析,通过CADisplayLink逐帧进行提取、播放,判断NSData是否为gif图的方法如下:


-(void)isGifData:(NSData *)data {

  BOOL hasData = ([data length] > 0);
  if (!hasData) {
      return NO;
  }
  CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data,
                                                            (__bridge CFDictionaryRef)@{(NSString *)kCGImageSourceShouldCache: @NO});
  // Early return on failure!
  if (!imageSource) {
      return NO;
  }

  // Early return if not GIF!
  //关键未知
  CFStringRef imageSourceContainerType = CGImageSourceGetType(imageSource);
  BOOL isGIFData = UTTypeConformsTo(imageSourceContainerType, kUTTypeGIF);
  return isGIFData;
}
///参考第三方库FLAnimatedImage中FLAniamtedImage.m
///- (instancetype)initWithAnimatedGIFData:(NSData *)data optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled

(此方法稍微改造一下还可以同时识别PNG/JPEG)

而精灵表单的本质上是一张大的图片,是将所有帧的图像堆到同一张图片里,只需要在一定间隔内读取指定小区域的照片,利用人眼视觉残留的特性,即可呈现动画效果,本文将探讨如何将此类图转为gif。

//相关参数,根据实际情况自行赋值,省略
CGFloat frameDurations;//帧间隔,单位为秒
NSMutableArray <NSValue *>* frameRects;//每一帧在大图中的区域
NSURL *savePathURL;//保存gif图片地址
UIImage *image;//sprite sheet大图

//gif图的参数
NSDictionary *fileSetting = @{
    (__bridge id)kCGImagePropertyGIFDictionary: @{
        (__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
    }
};

NSDictionary *frameSetting = @{
    (__bridge id)kCGImagePropertyGIFDictionary: @{
        (__bridge id)kCGImagePropertyGIFDelayTime: @(frameDurations), // a float (not double!) in seconds, rounded to centiseconds in the GIF data
    }
};
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)savePathURL, kUTTypeGIF, frameRects.count, NULL);
    CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileSetting);

//开始处理
for (int i = 0; i < frameRects.count; i ++) {
    CGRect rect = contentRects[i].CGRectValue;
    @autoreleasepool {
        //及时释放循环中累计的内存
        CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
        
        CGImageDestinationAddImage(destination, subImageRef, (__bridge CFDictionaryRef)frameSetting);
        CGImageRelease(subImageRef);
    }
}
//善后
if (!CGImageDestinationFinalize(destination)) {
    NSLog(@"failed to finalize image destination");
}
CFRelease(destination);

//生成gif
NSData *fileData = [[NSData alloc] initWithContentsOfURL:savePathURL];
//根据情况是否删除缓存文件

此段代码参考从视频中截取缩略图生成gif图片

还可以改进的地方:文中实现了图片->gif类型data的转换,需要将整个动画生成后才能对其做下一步的操作(比如显示动画),但实际上我们还可以通过CADisplayLink实时显示截取对应帧数的区域.

posted @ 2021-05-02 07:31  MrYu4  阅读(159)  评论(0编辑  收藏  举报