我正在尝试在NSImageView框中显示CGImage,但我无法将CGImage转换为NSImage。我应该如何处理这种情况?谢谢!
部分参考 Larme 的评论:
for Swift, the NSImage initializer that takes a CGImage is init(cgImage:size:)
and a syntax example is:
let myNsImage = NSImage(cgImage: myCgImage, size: .zero)
.zero
is a convenience for using the same size as the CGImage.
for Objective-C, see Getting NSImage from CGImageRef.
作为简化演示(有意使用 !
),这个 macOS Playground 将以可视化方式呈现与编程生成的 cgImage
相同的 nsImage
:
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
init(CGImage cgImage: CGImage, size size: NSSize)
? https://dev59.com/gGox5IYBdhLWcg3wmFaV ?这段文字介绍了一个在苹果开发中常用的类NSImage的初始化方法init(CGImage cgImage: CGImage, size size: NSSize)
,并提供了一个指向使用该方法获取NSImage对象的Stack Overflow问题链接。 - Larme