【问题标题】:Can't create an NSBitmapImageRep in Swift无法在 Swift 中创建 NSBitmapImageRep
【发布时间】:2014-11-17 18:04:43
【问题描述】:

我有一个使用 xcode 6.1 创建的 osx xcode 项目 我想用它来训练一下使用 SWIFT。

在我的一个观点中,我尝试创建一个 NSBitMapImageRep,如下所示:

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()
}}

但是每次我尝试运行它时,我都会收到以下错误:

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

我猜这是因为 bitmapDataPlanes 为零。但它是一个可选值,根据文档允许为 NULL。但是传递 NSNull() 不会编译。

谁能告诉我我必须通过什么? o_O

【问题讨论】:

    标签: xcode macos swift nsbitmapimagerep


    【解决方案1】:

    该错误实际上是相当具有描述性的 - 您为初始化程序提供了一组不一致的值。具体来说,samplesPerPixel 值 1 不支持您在 colorSpaceName 中指定的 RGB 颜色空间。 From here:

    samplesPerPixel:数据分量的数量,或每个像素的样本数。此值包括颜色分量和覆盖分量 (alpha)(如果存在)。有意义的值范围从 1 到 5。具有青色、品红色、黄色和黑色 (CMYK) 颜色分量加上覆盖分量的图像的 spp 为 5;缺少覆盖组件的灰度图像的 spp 为 1。

    所以你只需要将每像素的样本数改为 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)!
    

    【讨论】:

    • 虽然您的答案是正确的,但我认为该错误的描述性不是很强...详细的错误描述了“在展开可选值时意外发现 nil”,这使得错误看起来完全在某个地方else...主要在bitmapDataPlanes...
    • 您正在对可失败的初始化程序 (init?) 进行强制解包 (!)。在这种情况下,这实际上是一个非常常见的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多