【问题标题】:Fastest way to draw offscreen CALayer content绘制屏幕外 CALayer 内容的最快方法
【发布时间】:2017-09-04 02:21:13
【问题描述】:
我正在寻找在 macOS 上绘制屏幕外 CALayer 内容(不需要 alpha)的最快方法。请注意,这些示例不是线程化的,但重点是(以及为什么我不只是使用 CALayer.setNeedsDisplay)因为我是在后台线程上绘制的。
我的原始代码是这样做的:
let bounds = layer.bounds.size
let contents = NSImage(size: size)
contents.lockFocusFlipped(true)
let context = NSGraphicsContext.current()!.cgContext
layer.draw(in: context)
contents.unlockFocus()
layer.contents = contents
【问题讨论】:
标签:
core-graphics
core-animation
【解决方案1】:
我目前的最好成绩要快一些:
let contentsScale = layer.contentsScale
let width = Int(bounds.width * contentsScale)
let height = Int(bounds.height * contentsScale)
let bytesPerRow = width * 4
let alignedBytesPerRow = ((bytesPerRow + (64 - 1)) / 64) * 64
let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: alignedBytesPerRow,
space: NSScreen.main()?.colorSpace?.cgColorSpace ?? CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
)!
context.scaleBy(x: contentsScale, y: contentsScale)
layer.draw(in: context)
layer.contents = context.makeImage()
欢迎提供使其更好/更快的提示和建议。