ch_*_*end 4 nsimage cgimage swift
我正在尝试在 NSImageView 框中显示 CGImage,但在将 CGImage 转换为 NSImage 时遇到问题。我该如何应对这种情况?谢谢你!
部分基于 Larme 的评论:
对于 Swift,接受 CGImage 的 NSImage 初始值设定项是init(cgImage:size:),语法示例是:
let myNsImage = NSImage(cgImage: myCgImage, size: .zero)
Run Code Online (Sandbox Code Playgroud)
.zero是为了方便使用与 CGImage 相同的尺寸。
对于 Objective-C,请参阅从 CGImageRef 获取 NSImage。
作为一个简化的演示(!有意),这个 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3728 次 |
| 最近记录: |