gpt4 book ai didi

swift - 将 CGImage 转换为 NSImage Swift

转载 作者:行者123 更新时间:2023-12-04 17:58:12 24 4
gpt4 key购买 nike

我试图在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com