绘制屏幕外CALayer内容的最快方法 [英] Fastest way to draw offscreen CALayer content

查看:99
本文介绍了绘制屏幕外CALayer内容的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在macOS上绘制屏幕外CALayer内容(无需Alpha)的最快方法。请注意,这些示例不是线程化的,但重点是(以及为什么我不仅仅使用CALayer.setNeedsDisplay),因为我是在后台线程上进行绘制的。

I'm looking for the fastest way to draw offscreen CALayer content (no alpha needed) on macOS. Note, that these examples aren't threaded, but the point is (and why I'm not just using CALayer.setNeedsDisplay) because I'm doing this drawing on a background thread.

我的原始代码是这样做的:

My original code did this:

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


推荐答案

我的当前的最佳速度要快得多:

My current best is quite a bit faster:

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()

欢迎提出一些提示和建议,以使其变得更好/更快。

Tips and recommendations for making it better/faster are welcome.

这篇关于绘制屏幕外CALayer内容的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆