4

I am trying to display a CGImage in a NSImageView box and I am having trouble converting the CGImage to a NSImage. How should I approach this situation ? Thank you!

ch_studend
  • 91
  • 2
  • 10
  • 3
    https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSImage_Class/#//apple_ref/occ/instm/NSImage/initWithCGImage:size: `init(CGImage cgImage: CGImage, size size: NSSize)`? http://stackoverflow.com/questions/9098388/getting-nsimage-from-cgimageref ? – Larme Jul 26 '16 at 09:10
  • thank you very much! Apparently I ignored the proper initialization of the NSSize parameter when I tried the init... :D – ch_studend Jul 26 '16 at 09:19

1 Answers1

5

Partially based on Larme's comment:

  • for Swift, the NSImage initializer that takes a CGImage is init(cgImage:size:) and a syntax example is:

    let myNsImage = NSImage(cgImage: myCgImage, size: .zero)
    

    .zero is a convenience for using the same size as the CGImage.

  • for Objective-C, see Getting NSImage from CGImageRef.

And as a simplified demonstration (! on purpose), this macOS Playground will visually render nsImage identically to the programmatically generated cgImage:

import AppKit
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
let s: UInt32 = 0xffbbbbbb, o: UInt32 = 0xff3d85e6, f: UInt32 = 0x00000000
let width = 12; let height = 15
var pixels = [
    f, f, f, f, f, f, f, o, f, f, f, f, f, f, f, f, f, f, f, o, f, f, f, f, f, f, f, f, f, f, f, f, o, f, f, f, f, f, f, o, f, f, f, f, o, f, f, f, f, f, f, f, o, f, f, f, f, o, f, f, f, f, f, f, f, o, f, f, f, o, f, f, f, f, f, f, f, f, o, f, f, f, o, f, f, f, f, f, f, f, f, o, o, f, f, o, f, f, o, o, f, f, f, f, f, o, o, f, f, f, f, f, o, o, o, o, f, f, f, f, s, f, f, f, f, f, f, f, o, o, f, s, s, f, f, f, f, f, f, f, f, f, f, s, s, f, o, o, o, o, o, o, o, o, f, s, s, f, f, f, f, f, f, f, f, f, f, s, s, s, s, s, s, s, s, s, s, s, s, s,
]
var context: CGContext!
pixels.withUnsafeMutableBufferPointer { bufferPointer in
    context = CGContext(data: bufferPointer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil)
}
let cgImage = context.makeImage()!
let nsImage = NSImage(cgImage: cgImage, size: .zero)
_ = nsImage
Cœur
  • 37,241
  • 25
  • 195
  • 267