NSImage.cgImage(forProposedRect:context:hints:) 中的 proposedRect 是什么意思?
What does proposedRect mean in NSImage.cgImage(forProposedRect:context:hints:)?
我正在研究这个方法,因为我想将一个相当大的 NSImage 转换为一个较小的 CGImage,以便将它分配给 CALayer 的内容。
从 Apple's documentation 我知道 proposedRect 应该是将要返回的 CGImage 的大小,如果我为 proposedRect 传递 nil
,我将得到一个 CGImage原始 NSImage 的大小。 (如有错误请指正。)
我尝试用 nil
调用它作为建议的矩形,它工作得很好,但是当我尝试给它一些像 (0,0,400,300)
这样的矩形时,生成的 CGImage 仍然是原始图像的大小.我使用的代码如下。
var r = NSRect(x: 0, y: 0, width: 400, height: 300)
let img = NSImage(contentsOf: url)?.cgImage(forProposedRect: &r, context: nil, hints: nil)
一定是我理解错了。真希望有人能告诉我那是什么。
此方法不适用于生成缩放图像。基本思想是将 NSImage
绘制到上下文中的输入矩形会产生一定的结果。此方法创建一个 CGImage
,如果在同一上下文中将其绘制 到输出矩形 ,它会产生相同的结果。
因此,return CGImage
原始图像大小的方法完全有效。当 CGImage
被绘制到矩形时会发生缩放。
有一些关于此的文档仅存在于首次引入时的 historical release notes 中。搜索 "NSImage, CGImage, and CoreGraphics impedance matching".
要生成 scaled-down 图像,您应该创建一个所需大小的新图像,将焦点锁定在它上面,然后将原始图像绘制到它上面。或者,如果您不知道,您可以将原始图像指定为图层的 contents
并查看其性能是否足够。
我正在研究这个方法,因为我想将一个相当大的 NSImage 转换为一个较小的 CGImage,以便将它分配给 CALayer 的内容。
从 Apple's documentation 我知道 proposedRect 应该是将要返回的 CGImage 的大小,如果我为 proposedRect 传递 nil
,我将得到一个 CGImage原始 NSImage 的大小。 (如有错误请指正。)
我尝试用 nil
调用它作为建议的矩形,它工作得很好,但是当我尝试给它一些像 (0,0,400,300)
这样的矩形时,生成的 CGImage 仍然是原始图像的大小.我使用的代码如下。
var r = NSRect(x: 0, y: 0, width: 400, height: 300)
let img = NSImage(contentsOf: url)?.cgImage(forProposedRect: &r, context: nil, hints: nil)
一定是我理解错了。真希望有人能告诉我那是什么。
此方法不适用于生成缩放图像。基本思想是将 NSImage
绘制到上下文中的输入矩形会产生一定的结果。此方法创建一个 CGImage
,如果在同一上下文中将其绘制 到输出矩形 ,它会产生相同的结果。
因此,return CGImage
原始图像大小的方法完全有效。当 CGImage
被绘制到矩形时会发生缩放。
有一些关于此的文档仅存在于首次引入时的 historical release notes 中。搜索 "NSImage, CGImage, and CoreGraphics impedance matching".
要生成 scaled-down 图像,您应该创建一个所需大小的新图像,将焦点锁定在它上面,然后将原始图像绘制到它上面。或者,如果您不知道,您可以将原始图像指定为图层的 contents
并查看其性能是否足够。