Search code examples
swiftmacoscocoansimage

Add CATextLayer on Top of NSImageView


I'm trying to display text on top of an NSImage.I use the following code

                    let myTextLayer = CATextLayer()
                    myTextLayer.string = "My text"
                    myTextLayer.foregroundColor = NSColor.cyan.cgColor
                    myTextLayer.frame = self.img_view.bounds
                    self.img_view.layer=myTextLayer;

This keeps producing empty NSImageView


Solution

  • You needs explicitly say NSImageView wantsLayer before use layers, like below

    self.img_view.wantsLayer = true
    
    let myTextLayer = CATextLayer()
    myTextLayer.string = "My text"
    myTextLayer.foregroundColor = NSColor.cyan.cgColor
    myTextLayer.frame = self.img_view.bounds
    
    self.img_view.layer.addSublayer(myTextLayer)