Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a background image in cocoa NSView

I have found several answers on the question how you can set a background image to a UIView in iOS. However I was not able to solve this question for macOS and especially for cocoa. I have tried to set up something like

let bgImage = NSImage(named: "streaks")
let pattern = NSColor(patternImage: bgImage!)
self.view.layer?.background = pattern as! CGColor // this will fail on runtime
like image 650
Oliver Koehler Avatar asked Jan 23 '26 09:01

Oliver Koehler


2 Answers

Unlike UIView NSView is not layer backed by default, you have to enable it.

self.view.wantsLayer = true

Then create the image and assign it to the contents property of the layer.

let image = NSImage(named: "streaks")
self.view.layer!.contents = image
like image 109
vadian Avatar answered Jan 25 '26 01:01

vadian


In Swift 4

    self.view.wantsLayer = true
    let image = NSImage(named: NSImage.Name(rawValue: "streaks"))
    self.view.layer!.contents = image
like image 43
Steve Butabi Avatar answered Jan 25 '26 02:01

Steve Butabi