使用UIImages创建一个gif

时间:2015-10-08 18:19:30

标签: ios objective-c gif cgimage

我指的是post。我正在尝试使用屏幕截图创建的图像制作一个gif文件。我正在使用计时器来创建屏幕快照,以便获得可用于创建gif的所需帧数。我每0.1秒拍摄一次快照(我将在3秒后结束这个计时器)。

这是我拍摄UIView快照的代码:

-(void)recordScreen{

   self.timer= [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(takeSnapShot) userInfo:nil repeats:YES];

}

-(void)takeSnapShot{

    //capture the screenshot of the uiimageview and save it in camera roll
    UIGraphicsBeginImageContext(self.drawView.frame.size);
    [self.drawView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

}

和我所指的帖子,显示了一个帮助函数来创建gif。我不知道应该如何将我的图像传递给辅助函数。这是我试过的:

我试图修改这部分:

 static NSUInteger kFrameCount = 10;
 for (NSUInteger i = 0; i < kFrameCount; i++) {
        @autoreleasepool {
            UIImage *image = [self takeSnaphot];
            CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
        }
    }

这会创建包含10帧UIView的gif。

现在...

我要做的是:

我正在使用UIView在我的UIBeizerPath上用手指绘制一个简单的绘图,并且我将快照与我的绘图并行拍摄,这样我将有大约50-100个PNG文件。我试图将所有这些图像传递给makeGifMethod。

的工作流程:

  1. 启动应用程序。
  2. 点击启动计时器的按钮,每0.1秒拍摄一次照片
  3. 用手指画(所以所有的绘图都将被捕获,每秒0.1秒)
  4. 在每个快照之后,我调用makeanimatedgif方法,以便将拍摄的快照添加到gif文件中的上一帧
  5. 停止一切
  6. 问题:

    - 案例1:

    1. 点击按钮(确实创建了gif immediatley)
    2. 开始绘图
    3. 停止
    4. 检查gif(带有10帧的gif是用白色背景创建的,因为当我按下按钮时什么也没画出来)
    5. 如果我在循环中调用我的snapShot方法,我会获得绘图的最后10帧,但不是所有内容。

      for (NSUInteger i = 0; i < 10; i++) {
              @autoreleasepool {
                  UIImage *image = [self takeSnapShot];
                  CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
              }
          }
      

      - 案例2:

      1. 点击按钮(启动计时器,拍摄快照,与其并行调用makeGifMethod)
      2. 画出一些东西
      3. 停止
      4. 检查gif(空gif是在没有任何帧的情况下创建的,我每隔0.1秒调用makeGifMethod就不会按预期工作)
      5. 以下是案例2:

        的代码
          -(void)recordScreen{
        
           self.timer= [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(takeSnapShot) userInfo:nil repeats:YES];
        
        }
        
         -(void)takeSnapShot{
        
            //capture the screenshot of the uiimageview and save it in camera roll
            UIGraphicsBeginImageContext(self.drawView.frame.size);
            [self.drawView.layer renderInContext:UIGraphicsGetCurrentContext()];
            UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [self makeAnimatedGif:(UIImage *)viewImage];
        
            });
        
        } 
        
        
        -(void) makeAnimatedGif:(UIImage *)image{
        
            NSDictionary *fileProperties = @{
                                             (__bridge id)kCGImagePropertyGIFDictionary: @{
                                                     (__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
                                                     }
                                             };
        
            NSDictionary *frameProperties = @{
                                              (__bridge id)kCGImagePropertyGIFDictionary: @{
                                                      (__bridge id)kCGImagePropertyGIFDelayTime: @0.02f, // a float (not double!) in seconds, rounded to centiseconds in the GIF data
                                                      }
                                              };
        
            documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
            fileURL = [documentsDirectoryURL URLByAppendingPathComponent:@"animated.gif"];
        
            CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF, 10, NULL);
            CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileProperties);
        
                    CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
        
            if (!CGImageDestinationFinalize(destination)) {
                NSLog(@"failed to finalize image destination");
            }
            CFRelease(destination);
        
            NSLog(@"url=%@", fileURL);
        }
        

        有人可以建议我如何将捕获的图像传递给上面的方法制作一个gif?

1 个答案:

答案 0 :(得分:4)

经过几次解决后,我选择将所有捕获的图像存储到一个数组中,然后使用该数组将图像传递给gifMethod。它工作得很酷!!!

我已将所有图像存储到数组中:

-(void)takeSnapShot{

//capture the screenshot of the uiimageview and save it in camera roll
UIGraphicsBeginImageContext(self.drawView.frame.size);
[self.drawView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//store all the images into array
[imgArray adDObject:viewImage]; 

} 

注意:确保在将图像存储到阵列之前调整图像大小,否则可能会出现内存警告,如果长时间使用,则会导致应用程序崩溃。

以后使用相同的数组:

-(void)makeAnimatedGif {
    NSUInteger kFrameCount = imgArray.count;

    NSDictionary *fileProperties = @{
                                     (__bridge id)kCGImagePropertyGIFDictionary: @{
                                             (__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
                                             }
                                     };

    NSDictionary *frameProperties = @{
                                      (__bridge id)kCGImagePropertyGIFDictionary: @{
                                              (__bridge id)kCGImagePropertyGIFDelayTime: @0.08f, // a float (not double!) in seconds, rounded to centiseconds in the GIF data
                                              }
                                      };

    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
    NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:@"animated.gif"];

    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF, kFrameCount, NULL);
    CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileProperties);

    for (NSUInteger i = 0; i < kFrameCount; i++) {
        @autoreleasepool {
            UIImage *image =[imgArray objectAtIndex:i];  //Here is the change
            CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
        }
    }

    if (!CGImageDestinationFinalize(destination)) {
        NSLog(@"failed to finalize image destination");
    }
    CFRelease(destination);

    NSLog(@"url=%@", fileURL);

  }