[英]Rotating UIView including the CALayer bounds AND the CALayer frame
我想使用UIDeviceOrientationDidChangeNotification
旋转我的“containerView”UIView(截图中的半透明红色框),然后稍后(在它旋转之后)将子图层添加到视图的图层,但我发现只调整了containerView.layer的边界大小,而不是containerView.layer的框架! :(
这是它在肖像中的样子:
示例代码:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidAppear:(BOOL)animated
{
CALayer *r = [CALayer layer];
r.frame = CGRectMake(0, 0, 100, 100);
r.contents = (id)[[UIImage imageNamed:@"r.png"] CGImage];
[self.containerView.layer addSublayer:r];
}
- (void)deviceRotated:(NSNotification *)notification
{
...
if (orientation == UIDeviceOrientationLandscapeLeft) {
self.containerView.transform = CGAffineTransformMakeRotation(RADIANS(90));
self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);
NSLog(@"container bounds: %@", NSStringFromCGRect(self.containerView.bounds));
NSLog(@"container layer frame: %@", NSStringFromCGRect(self.containerView.layer.frame));
NSLog(@"container layer bounds: %@", NSStringFromCGRect(self.containerView.layer.bounds));
CALayer *testLayer = [CALayer layer];
testLayer.backgroundColor = [[UIColor blueColor] CGColor];
testLayer.bounds = self.containerView.layer.frame;
testLayer.position = CGPointMake(CGRectGetMidX(testLayer.bounds), CGRectGetMidY(testLayer.bounds));
[self.containerView.layer addSublayer:testLayer];
}
}
旋转后打印:
container bounds: {{0, 0}, {411, 320}}
container layer frame: {{0, 0}, {320, 411}}
container layer bounds: {{0, 0}, {411, 320}}
(注意图层的帧仍然是320宽,411高。)
所以现在它看起来像:
我也尝试在更改边界之前设置中心,但看起来像:
我知道containerView的图层没有自动调整大小,所以我尝试在变换后设置图层的框架... self.containerView.layer.frame = self.containerView.bounds;
然后打印出来:
container bounds: {{0, 0}, {320, 411}}
container layer frame: {{0, 0}, {411, 320}}
container layer bounds: {{0, 0}, {320, 411}}
看起来像:
哎呀!
所有视图的autoResizesSubviews都设置为YES,clipsToBounds设置为NO。 我不能使用shouldAutorotateToInterfaceOrientation
因为真正的应用程序将有一个相机预览,所以我希望根视图保持纵向。
我必须错过一些关于我如何在containerView上进行转换以使其图层的边界和框架相同的东西,但我无法弄清楚它是什么! 任何帮助将非常感激。
更新 - 修正:
设置新添加图层边界( testLayer.bounds
)到contentView.layer.bounds
代替contentView.layer.frame
的伎俩。 (因为转换contentView会使其layer.frame失效。)谢谢迈克尔!
固定:
self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);
由于翻转的上下文,您在此处的设置是错误的。 您将其设置为宽,因为它翻转90度后会回到垂直状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.