Can't create an NSBitmapImageRep in Swift

3.1k views Asked by At

I've got an osx xcode project created with xcode 6.1 I wanted to use it to train using with SWIFT a little bit.

In one of my views I tried creating an NSBitMapImageRep as seen here:

class BitmapView : NSView {
var image: NSBitmapImageRep!

override func awakeFromNib() {
    var blub = NSBitmapImageRep(bitmapDataPlanes: nil,
        pixelsWide: Int(self.frame.size.width),
        pixelsHigh: Int(self.frame.size.height),
        bitsPerSample: 8,
        samplesPerPixel: 1,
        hasAlpha: false,
        isPlanar: false,
        colorSpaceName: NSCalibratedRGBColorSpace,
        bytesPerRow: 0, bitsPerPixel: 0)!

    //test()
}}

But every time I try running it, I get the following error:

Inconsistent set of values to create NSBitmapImageRep fatal error: unexpectedly found nil while unwrapping an Optional value

Which I guess is due to bitmapDataPlanes being nil. But it is an optional value and according to the documentation is allowed to be NULL. Passing NSNull() instead doesn't compile though.

Can anybody tell me what I would have to pass instead? o_O

1

There are 1 answers

2
Nate Cook On BEST ANSWER

The error is actually fairly descriptive - you're providing an inconsistent set of values to the initializer. Specifically, the samplesPerPixel value of 1 can't support a RGB color space, which you specify in colorSpaceName. From here:

samplesPerPixel: The number of data components, or samples per pixel. This value includes both color components and the coverage component (alpha), if present. Meaningful values range from 1 through 5. An image with cyan, magenta, yellow, and black (CMYK) color components plus a coverage component would have an spp of 5; a grayscale image that lacks a coverage component would have an spp of 1.

So you just need to change the samples per pixel to 3:

var blub = NSBitmapImageRep(bitmapDataPlanes: nil,
    pixelsWide: Int(100),
    pixelsHigh: Int(100),
    bitsPerSample: 8,
    samplesPerPixel: 3,
    hasAlpha: false,
    isPlanar: false,
    colorSpaceName: NSCalibratedRGBColorSpace,
    bytesPerRow: 0, bitsPerPixel: 0)!