5

I want to show an animated gif image in my cocoa application.

I dragged the gif into Assets.xcassets in XCode. I was hoping that NSImageView can show a gif out of the box, so I tried the following code.

let imageView = NSImageView(frame: NSRect(x: 0, y: 0, width: 512, height: 512))
imageView.canDrawSubviewsIntoLayer = true
imageView.imageScaling = .ScaleNone
imageView.animates = true
imageView.image = NSImage(named: "loading-animation")

window.contentView?.addSubview(imageView)

The image does not show up. The above code works with a png image. How do I get this to work?

0

4 Answers 4

6

For me it works only if there is nothing set in the Attribute Inspector and with the code like that (hope, it will be useful for someone):

class FirstViewController: NSViewController {  

  @IBOutlet weak var imgImage1: NSImageView!

 override func viewDidLoad() {
        super.viewDidLoad()

let imgImage1 = NSImageView(frame: NSRect(x: 407, y: 474, width: 92, height: 74))
        imgImage1.canDrawSubviewsIntoLayer = true
        imgImage1.imageScaling = .scaleProportionallyDown
        imgImage1.animates = true
        imgImage1.image = NSImage(named: "mygif")
        self.view.addSubview(imgImage1)
}

Enjoy :)

5

Xcode 12

  1. Just add your gif file in your project (Not in Assets)
  2. Add an NSImageView in your view controller.
  3. Set the image name in the storyboard as your gif file name.
  4. Tap on Animates property.

enter image description here

4

Answering my own question.

I was able to make a gif display in my app when I get the gif from a URL e.g.

imageView.image = NSImage(byReferencingURL: yourgifurl)

So, I figured there was something wrong with the way I copied the image into my project. Instead of putting the image in Assets.xcassets, I put it with the rest of source code and the gif shows up :) (but the animation speed seems to be very slow)

1
  • Did you ever find out what the issue is with the slow playback speed? I"m having that same problem...
    – peterflynn
    Commented Sep 10, 2018 at 21:18
1

Suppose you have an animated gif resource named universe in an Assets.xcassets and NSImageView connected by IBOutlet named target:

...
@IBOutlet weak var target: NSImageView!
...

func applicationDidFinishLaunching(_ aNotification: Notification) {
    ...
    target.animates = true
    target.image = NSImage(data: NSDataAsset(name: "universe")!.data)
    ...
}

NOTE:

target.image = NSImage(named: "universe") // WILL NOT WORK!
1
  • NSDataAsset only available from 10.11. What should I use for 10.10?
    – prabhu
    Commented Feb 24, 2020 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.