我知道,当使用以下代码片段创建图像并将其分配给 View 层的内容时,当 View 的支持属性更改时,即窗口移入或移出视网膜显示器时,渲染 block 会自动再次执行。
[NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) {
CGContextRef const context = NSGraphicsContext.currentContext.graphicsPort;
....
return YES;
}];
在这个渲染 block 内,我试图将另一个 NSImage 垂直居中。我希望它在高分辨率显示器上看起来尽可能居中,但在非视网膜屏幕上不模糊。因此我想知道是否有任何方法可以找出图像渲染时使用的 contentScaleFactor。
这确实应该很简单,但即使经过几个小时的尝试和搜索互联网,我也没有找到一种方法来确定图像是否正在为视网膜屏幕渲染。
最佳答案
来自High Resolution Guidelines for OS X: APIs for Supporting High Resolution — Getting Scale Information :
CGContextRef
The preferred way to get the scaling information for a CGContext object is to call the conversion function
CGContextConvertRectToDeviceSpace
:deviceRect = CGContextConvertRectToDeviceSpace(context, userRect);
Then you can divide
deviceRect.size.height
byuserRect.size.height
. This works for both implicitly scaled window contexts and explicitly scaled bitmap contexts.
不过,我实际上认为您不应该计算比例。我认为你应该从用户空间转换为设备空间,将 rect
参数转换为绘图处理程序,并使用任意原点(NSZeroPoint
即可)和大小构造一个 rect您尝试居中的图像的位置。调整后者的原点,以在设备空间中以数学方式将其置于前者的中心。使用 NSIntegralRectWithOptions()
对结果进行积分。然后,使用 CGContextConvertRectToUserSpace()
将其转换回用户空间。将图像绘制到生成的矩形中。
关于retina-display - NSImage 的 DrawingHandler 和视网膜屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26263914/