UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Adding an NSImage to NSView as a CALayer

Forums > macOS

I'm having trouble getting a disk image to be displayed in a CALayer as an NSImage in a NSView. I'm trying to build a view as a letter sized page to eventually turn into a PDF.

import Cocoa

class Page: NSView {
   func insertImage(view: NSView) -> NSView {
           /*
            Method adds a background image to the view
            */

           let backgroundLayer = CALayer()
           backgroundLayer.bounds = CGRect(x: 0, y: 0, width: 72*8.5, height: 72*11)
           backgroundLayer.position = CGPoint(x: 0, y: 0)
           backgroundLayer.contents = NSImage(named: "/Users/Shared/background.png")
           print(backgroundLayer.contents) // <--- This is showing as nil
           backgroundLayer.contentsGravity = .resizeAspectFill
           backgroundLayer.masksToBounds = true

           view.layer?.addSublayer(backgroundLayer)

           return view
    }
 }

This is my viewcontroller.swift:

 import Cocoa

 class ViewController: NSViewController {

    let page = Page()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.wantsLayer = true // https://stackoverflow.com/questions/51859378/nsview-and-calayer
        self.view = page.insertImage(view: self.view)
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.

        }
    }

}

I followed the same examples I have found on SO, but it's not working for me. I threw in a print() statement to see if it's even reading the file and it is showing nil. Does this have to do with permissions or something? I'm not getting any build or runtime errors.

3      

I have no idea why, but this is now working after moving the file to my Downloads folder. I got a promt to allow the program to access files in my Downloads folder. I thought /Users/Shared was a free-for-all and wasn't Sandboxed? That is where I've done all my development. How do I give XCode permission to read/write data in /Users/Shared?

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.