将CGImage转换为NSImage Swift

时间:2016-07-26 09:07:44

标签: swift nsimage cgimage

我正在尝试在NSImageView框中显示CGImage,但我无法将CGImage转换为NSImage。我应该如何处理这种情况?谢谢!

1 个答案:

答案 0 :(得分:1)

部分基于 Larme 的 comment

  • 对于 Swift,采用 CGImage 的 NSImage 初始值设定项是 init(cgImage:size:),语法示例是:

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

    .zero 方便使用与 CGImage 相同的大小。

  • 对于 Objective-C,请参阅 Getting NSImage from CGImageRef

作为一个简化的演示(故意使用 !),这个 macOS Playground 将在视觉上呈现与以编程方式生成的 nsImage 相同的 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
相关问题