macoscocoagifnsimageview

How to animate a GIF image in Cocoa and set it to not loop.


Just as my title mentions, I want to use NSImageView, To "animate" an image, but not loop when it reaches the end of its animation.


Solution

  • The infinite loop of a gif image is not a bad habit of the NSImageView, it is determined by a value (in Application Extension) within the gif image data. You can ask for that value by

    NSBitmapImageRep *gifRep = // get the gif image from wherever
    NSInteger loopCount = [[gifRep valueForProperty: NSImageLoopCount] integerValue];
    // a lopCount of zero means: infinite
    

    But you can also set that value (before sending it to the NSImageView). If you want the animation to stop after one loop, do this:

    NSImage *img = [[NSImage alloc] initWithContentsOfFile:fileName]; // or similar
    NSBitmapImageRep *gifRep = [[img representations] objectAtIndex:0];
    [gifRep setProperty:NSImageLoopCount withValue:@(1)]; //one loop, then stop
    [myImageView setImage:img];