Search code examples
macoscocoaswift3calayernsimage

Cocoa CALayer not displaying NSImage


Having issues displaying a NSImage in a CALayer

 init(image: NSImage) {
     self.image = image
     super.init(frame: .zero)
 }

 required init(coder aDecoder: NSCoder) {
     fatalError("init(coder:) has not been implemented")
 }

 override func viewWillDraw() {
     super.viewWillDraw()
     animationLayer.contentsGravity = kCAGravityResizeAspect
     animationLayer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
     animationLayer.contents = image.cgImage
     animationLayer.masksToBounds = true
     animationLayer.backgroundColor = NSColor.blue.cgColor

     wantsLayer = true
     layer?.addSublayer(animationLayer)
 }

The CALayer with the backgroundColor set as blue is rendering fine, but the NSImage is not. The NSImage is confirmed as containing the required image and is set on initialisation of the class.

Having developed the same within the iOS Framework, I am struggling to see the difference.


Solution

  • Unlike in iOS the image property of CALayer in macOS considers NSImage rather than its CGImage representation.

    animationLayer.contents = image