我偶然发现了一件奇怪的事情。看起来像UIView
's contentScaleFactor
即使在 Retina 设备上也始终为 1,除非您实现drawRect:
。考虑这段代码:
@interface MyView : UIView
@end
@implementation MyView
- (id) initWithFrame: (CGRect) frame
{
self = [super initWithFrame: frame];
if (self) {
NSLog(@"%s %g %g %g", __PRETTY_FUNCTION__, self.contentScaleFactor, self.layer.contentsScale, [UIScreen mainScreen].scale);
}
return self;
}
- (void) didMoveToWindow
{
if (self.window)
NSLog(@"%s %g %g %g", __PRETTY_FUNCTION__, self.contentScaleFactor, self.layer.contentsScale, [UIScreen mainScreen].scale);
}
@end
在 Retina 设备上,它打印以下内容:
-[MyView initWithFrame:] 1 1 2
-[MyView didMoveToWindow] 1 1 2
如果我添加一个空的实现drawRect:
像这样:
- (void) drawRect: (CGRect) rect
{
}
它按预期工作:
-[MyView initWithFrame:] 2 2 2
-[MyView didMoveToWindow] 2 2 2
因此,看起来视图是否位于任何视图层次结构中以及它显示在哪种屏幕上并不重要。唯一重要的是视图是否实现drawRect:
or not.
这是一个错误还是一个功能?我知道我可以改变didMoveToWindow
如下修复它
- (void) didMoveToWindow
{
if (self.window)
self.contentScaleFactor = self.window.screen.scale;
}
但默认行为仍然让我烦恼。
你可能会问我为什么需要contentScaleFactor
如果我不画任何东西的话。那是因为我刚刚设置self.layer.contents
到现成的图像,然后用contentStretch
。但是,图像在 Retina 设备上无法正确拉伸,除非contentScaleFactor
设置正确,即使@2x
使用图像。准确地说,它可以正常工作unless a @2x
使用图像。我猜这是一个错误。
谁能分享您对原因的见解contentScaleFactor
有这样的行为吗?它仅适用于 iOS 5 吗?