swift - 将 CGImage 转换为 NSImage Swift

标签 swift nsimage cgimage

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

最佳答案

部分基于 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

关于swift - 将 CGImage 转换为 NSImage Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38585589/

相关文章:

cocoa - 在 Cocoa : How to open image, 中调整它的大小并用新名称保存

swift - 在扩展函数中处理零计数 - 用于 image.results 中的结果

ios - 当使用 CGContext 缩放到小尺寸时,CGImage 的像素数据不完整

iphone - 如何在iPhone中保存大于设备分辨率的图像?

swift - 使用 Snapkit 的自定义 View 在使用时不显示

ios - 在 Swift 中 stub HTTP 请求

ios - 更改 iOS 图表中组合图表的绘图顺序

macos - Swift OS X - 将 .jpeg 保存到 NSImage 数组中

iphone - iOS iPhone CGImage 内存问题

ios - 如何使用 Swift 将字符串连同特殊字符和符号传递到 API 中?