Search code examples
objective-cmacosanimated-gifscreensaver

How to display a animated gif in a screen saver plugin?


Okay so I'm a new to objective-c. (irrelevant, but I'm looking forward to swift!:D) and I'm trying to create a screen saver plugin that will display an animated gif.

My first attempt was to create NSBitmapImageRep and to get the individual frames from the representations property NSImageFrameCount and NSImageCurrentFrame after getting a NSData (TIFFRepresentation compressed format) object from an NSImage object that was inited with contents from url.

It failed miserably.

Second attempt I made actually worked, but it didn't animate the gif. It only displayed the first frame. What I did was create an NSImage with url contents and then called the drawInRect within the ScreenSaverView drawRect method.

I tried one more time before coming to stack overflow for help. Here is my current code: codebin

For my most recent try, I thought maybe creating an NSImageview setting the image to the NSImage inited with contents from url again and drawing the view in the ScreenSaverView draw method. But it's pointless, because I'm creating a view in a view for no reason.

I'm stuck now and my question is: How do you play an animated gif in a ScreenSaverView?


Solution

  • In a normal app context, you can just put an NSImageView in your view hierarchy, set its image to an NSImage loaded from an animating gif, and make sure the image view's animates property is YES. It might work to put such an image view in your ScreenSaverView and simply call [self setNeedsDisplay:YES] in its -animateOneFrame method.

    You would, of course, have to set the image view's frame correctly. To fill its superview, it should be set to its superview's bounds, not its frame. You would also want to set the autoresizing mask to make sure it tracks changes in the superview's size, and set the superview to autoresize its subviews, if it doesn't already. You would not override -drawRect: in your ScreenSaverView and definitely not invoke the image view's -drawRect: yourself. The image view will draw itself just as a consequence of being in the view hierarchy.