提问人:Chris Walken 提问时间:7/20/2023 更新时间:7/20/2023 访问量:17
在macOS中,可以对以NSImage为内容的CALayer进行编码/解码吗?
In macOS can a CALayer that has an NSImage as its contents be encoded / decoded?
问:
尝试解码使用 NSImage 编码的 CALayer 作为其 .contents,会在控制台中生成以下输出,并且解码后图像不在 CALayer 中。
<NSImage 0x600003390c80 Name=Rip Size={285, 298} RepProvider=<NSImageURLReferencingRepProvider:0x6000002da160 url:file:///Library/Developer/Xcode/DerivedData/CALayerTest-azbammleuklcsteocgqyjikdhnga/Build/Products/Debug/CALayerTest.app/Contents/Resources/Rip.jpg reps:(
"NSBitmapImageRep 0x60000299eae0 Size={285, 298} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=285x298 Alpha=NO Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x6000002da460"
)>>
For key: contents
生成的代码是 - NSKeyedUnarchiver.unarchiveTopLevelObjectWithData:
do {
theData = try NSKeyedArchiver.archivedData(withRootObject: theLayer, requiringSecureCoding: false)
}
catch {
print("that didnt work")
}
if let decodedLayer = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(theData) as? CALayer {
我猜这是行不通的。摘自 Apple 的核心动画编程指南(约 2015-03-09),它说:
使用图像作为图层内容
由于图层只是用于管理位图图像的容器,因此可以将图像直接分配给图层的 contents 属性。将图像分配给图层非常简单,并允许您指定要在屏幕上显示的确切图像。该图层使用您直接提供的图像对象,并且不会尝试创建该图像的自己的副本。如果应用在多个位置使用相同的图像,此行为可以节省内存。
我通过单独编码 NSImage 并复制 CALayer 并在编码之前将 .contents 设置为 nil 来解决它。(需要创建副本,因为 CALayers 可能附加到现有层)。然后,在加载数据时(在 CALayer 解码后),重新添加 NSImage。
不是 100% 确定这是正确的方法。
答: 暂无答案
评论