【发布时间】:2012-02-28 09:01:17
【问题描述】:
我偶然发现了一件奇怪的事情。看起来 UIView 的 contentScaleFactor 始终为 1,即使在 Retina 设备上也是如此,除非您实现 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:。
这是错误还是功能?我知道我可以更改didMoveToWindow 来修复它
- (void) didMoveToWindow
{
if (self.window)
self.contentScaleFactor = self.window.screen.scale;
}
但默认行为仍然困扰着我。
如果我不画任何东西,你可能会问我为什么需要contentScaleFactor。那是因为我只是将self.layer.contents 设置为一个现成的图像,然后用contentStretch 拉伸图像。但是,除非正确设置了 contentScaleFactor,否则即使使用了 @2x 图像,图像也不会在 Retina 设备上正确拉伸。准确地说,它可以正常工作除非使用@2x 图像。我猜这是一个错误。
任何人都可以分享您对contentScaleFactor 为何如此行事的见解吗?它是否仅适用于 iOS 5?
【问题讨论】:
标签: ios uiview retina-display