I am trying to create a CALayer to apply to my view. But, before I even get to that I cannot get an image to load from disk.
What am I doing wrong?
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let image = NSImage(contentsOfFile: "/Users/Shared/background.png")!
let imageView = NSImageView(image: image)
self.view.addSubview(imageView)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
I have used contentsOfFile as well as byReferencingFile and it doesn't change the behavior. The file exists at that path.
UPDATE: This doesn't work either.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let fileURL = URL(fileURLWithPath: "/Users/carroll/Desktop/background.jpg")
let image = NSImage(contentsOf: fileURL)
print(image)
let imageView = NSImageView(image: image)
self.view.addSubview(imageView)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
So this is what is printing to the console:
Optional(<NSImage 0x600003310aa0 Size={576, 828} Reps=( "NSBitmapImageRep 0x60000260e4c0 Size={576, 828} ColorSpace=(not yet > loaded) BPS=8 BPP=(not yet loaded) Pixels=2400x3450 Alpha=NO Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600000246a60" )>)
2020-08-10 11:46:57.767358-0500 My App[83208:8822749] Metal API Validation Enabled 2020-08-10 11:46:57.832881-0500 My App[83208:8822749] VPA info: plugin is INTEL, AVD_id = 1080010, AVD_api.Create:0x131373c15
From what I see above from the print statement it looks like it is getting the image, but it shows not loaded yet and then for the CurrentBacking it shows nil (faulting).
UPDATE 2 I was able to get the background to display, but I do not understand why this works and why I have to have set self.view.wantsLayer = true
when the Apple Documentation says this property is already set to true as default.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
let image = NSImage(contentsOf: URL(fileURLWithPath: "/Users/Shared/background.jpg"))
self.view.layer?.contents = image
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
I think you might be mixing up with the iOS behaviour.
iOS UIView
has wantsLayer
true
by default, whereas macOS NSView
has wantsLayer
false
by default (for backwards compatibility with older apps I suspect?).
For macOS you will need to manually set wantsLayer
on the view to true
to be able to use layers in your view.
(I know this is an older question but still begs an answer)